分享好友 站长动态首页 网站导航

MySQL默认值和约束的查询方法

2022-06-28 10:03 · 头闻号数据库

一、MySQL默认值相关查询

1. 列出 MySQL 数据库中的表默认值

select table_schema as database_name,
table_name,
column_name,
column_default
from information_schema.columns
where column_default is not null
and table_schema not in ('information_schema', 'sys',
'performance_schema','mysql')
-- and table_schema = 'your database name'
order by table_schema,
table_name,
ordinal_position;

说明:

2. MySQL数据库默认值汇总

select column_default,
count(distinct concat(col.table_schema, '.', col.table_name)) as tables,
count(column_name) as columns
from information_schema.columns col
join information_schema.tables tab on col.table_schema = tab.table_schema
and col.table_name = tab.table_name
where col.table_schema not in ('sys', 'information_schema',
'mysql', 'performance_schema')
and tab.table_type = 'base TABLE'
group by column_default
order by tables desc,
columns desc;

说明:

二、约束

1. 列出了数据库(模式)中的所有不可为空的列

select tab.table_schema as database_name,
tab.table_name,
col.ordinal_position as column_id,
col.column_name,
col.data_type,
case when col.numeric_precision is not null
then col.numeric_precision
else col.character_maximum_length end as max_length,
case when col.datetime_precision is not null
then col.datetime_precision
when col.numeric_scale is not null
then col.numeric_scale
else 0 end as 'precision'
from information_schema.tables as tab
join information_schema.columns as col
on col.table_schema = tab.table_schema
and col.table_name = tab.table_name
and col.is_nullable = 'no'
where tab.table_schema not in ('information_schema', 'sys',
'mysql','performance_schema')
and tab.table_type = 'base TABLE'
-- and tab.table_schema = 'database name'
order by tab.table_schema,
tab.table_name,
col.ordinal_position;

注意:如果您需要特定数据库(模式)的信息,请取消注释 where 子句中的条件并提供您的数据库名称。

说明:

2. 检查 MySQL 数据库中的列是否可为空

select c.table_schema as database_name,
c.table_name,
c.column_name,
case c.is_nullable
when 'NO' then 'not nullable'
when 'YES' then 'is nullable'
end as nullable
from information_schema.columns c
join information_schema.tables t
on c.table_schema = t.table_schema
and c.table_name = t.table_name
where c.table_schema not in ('mysql', 'sys', 'information_schema',
'performance_schema')
and t.table_type = 'base TABLE'
-- and t.table_schema = 'database_name' -- put your database name here
order by t.table_schema,
t.table_name,
c.column_name;

说明:

免责声明:本平台仅供信息发布交流之途,请谨慎判断信息真伪。如遇虚假诈骗信息,请立即举报

举报
反对 0
打赏 0
更多相关文章

评论

0

收藏

点赞