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'

根据库名导出所有表名及表备注

select
    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;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。