目录

一、环境

二、需求:获取某一表的字段信息

三、实现


一、环境

mysql5.7.20

二、需求:获取某一表的字段信息

现有表信息如下:

如何获取表的字段名?

三、实现

MySQL安装成功后可以看到已经存在mysql、information_schema和performance_schema等这个几个数据库,其中information_schema库中有名为COLUMNS的表,表中记录了数据库中所有表的字段信息:

通过该表,可以获取到某一表的字段信息:

-- SQL语句格式如下:
select COLUMN_NAME from information_schema.COLUMNS where table_name = 'your_table_name';

-- 其中,your_table_name是需要查询字段信息的表的名称,使用时自行修改。

例如,要查询customers表的字段信息,脚本如下:

select COLUMN_NAME from information_schema.COLUMNS where table_name = 'customers';

结果:

以上查询会存在一个问题。问题如下:

若多个数据库中存在同名表,则查询的结果会包括全部同名表的字段信息。比如:

因此,推荐使用以下更为严格的写法:

select COLUMN_NAME from information_schema.COLUMNS where table_name = 'your_table_name' and table_schema = 'your_db_name'; 

比如上面的例子,改成这样:

select COLUMN_NAME from information_schema.COLUMNS where table_name = 'customers' and table_schema = 'Populate';

若想取出所有字段,用一行显示(中间用英文逗号隔开),可以这样:

select group_concat(COLUMN_NAME SEPARATOR ',') AS t_info  from information_schema.COLUMNS where table_name = 'customers' and table_schema = 'Populate';

具体请查阅官网信息:https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_group-concat

 

 

Logo

更多推荐