MySQL基础:mysql数据库查看表结构的三种方法
mysql查看表结构
1. show create table
show create table 表名称
这个语句每次本能想出的,语义好记,可以直接查看建表语句,但不便于代码处理。
2. desc
desc 表名称
这个语句简单易用,可以获取到 COLUMNS 中的比较重要的字段:名称、类型、是否为空、键、默认值、额外信息。但无法获取字段的注释。
3. information_schema.COLUMNS
select * from information_schema.COLUMNS where TABLE_SCHEMA = ‘库名称’ and TABLE_NAME = ‘表名称’
相对show create table而言,相对简单,信息全面,可以查询出来字段的名称、类型、键、权限、注释和其他信息。为了获取字段名称,故我脚本中使用这个作为获取表结构的方法。
附:information_schema.COLUMNS字段和含义
字段名称及含义
TABLE_CATALOG
表类型(没搞懂干啥用?)TABLE_SCHEMA
所属库名称TABLE_NAME
表名称COLUMN_NAME
字段名称ORDINAL_POSITION
位置序号COLUMN_DEFAULT
默认值IS_NULLABLE
是否可为空DATA_TYPE
数据类型CHARACTER_MAXIMUM_LENGTH
字符串最大长度(数值类型为空)CHARACTER_OCTET_LENGTH
字符串最大存储长度(一般与上一字段相同)NUMERIC_PRECISION
数值精度(非数值类型为空)NUMERIC_SCALE
数值小数位数(非数值类型为空)DATETIME_PRECISION
日期精度CHARACTER_SET_NAME
编码方式COLLATION_NAME
排序方式COLUMN_TYPE
字段类型COLUMN_KEY
字段涉及的key(主键、唯一键等)EXTRA
其他(如 auto_increment)PRIVILEGES
权限COLUMN_COMMENT
字段注释GENERATION_EXPRESSION
代表达式(没搞懂,mysql可以表继承?)
获取所有的表结构及备注
根据库名导出所有表信息
SELECT
*
FROM
information_schema.`TABLES`
WHERE
TABLE_SCHEMA = ‘db_name’
*
FROM
information_schema.`TABLES`
WHERE
TABLE_SCHEMA = ‘db_name’
根据库名导出所有表名及表备注
SELECT
TABLE_NAME,
TABLE_COMMENT
FROM
information_schema.`TABLES`
WHERE
TABLE_SCHEMA = ‘db_name’;
TABLE_NAME,
TABLE_COMMENT
FROM
information_schema.`TABLES`
WHERE
TABLE_SCHEMA = ‘db_name’;
mysql获取整个库的所有表,及表结构
SELECT
TABLE_SCHEMA AS ‘库名’,
TABLE_NAME AS ‘表名’,
COLUMN_NAME AS ‘列名’,
ORDINAL_POSITION AS ‘列的排列顺序’,
COLUMN_DEFAULT AS ‘默认值’,
IS_NULLABLE AS ‘是否为空’,
DATA_TYPE AS ‘数据类型’,
CHARACTER_MAXIMUM_LENGTH AS ‘字符最大长度’,
NUMERIC_PRECISION AS ‘数值精度(最大位数)’,
NUMERIC_SCALE AS ‘小数精度’,
COLUMN_TYPE AS ‘列类型’,
COLUMN_KEY ‘KEY’,
EXTRA AS ‘额外说明’,
COLUMN_COMMENT AS ‘注释’
FROM
information_schema.`COLUMNS`
WHERE
TABLE_SCHEMA = ‘db_name’
ORDER BY
TABLE_NAME,
ORDINAL_POSITION;
TABLE_SCHEMA AS ‘库名’,
TABLE_NAME AS ‘表名’,
COLUMN_NAME AS ‘列名’,
ORDINAL_POSITION AS ‘列的排列顺序’,
COLUMN_DEFAULT AS ‘默认值’,
IS_NULLABLE AS ‘是否为空’,
DATA_TYPE AS ‘数据类型’,
CHARACTER_MAXIMUM_LENGTH AS ‘字符最大长度’,
NUMERIC_PRECISION AS ‘数值精度(最大位数)’,
NUMERIC_SCALE AS ‘小数精度’,
COLUMN_TYPE AS ‘列类型’,
COLUMN_KEY ‘KEY’,
EXTRA AS ‘额外说明’,
COLUMN_COMMENT AS ‘注释’
FROM
information_schema.`COLUMNS`
WHERE
TABLE_SCHEMA = ‘db_name’
ORDER BY
TABLE_NAME,
ORDINAL_POSITION;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。