MySQL默認值和約束的查詢方法
作者:雪竹頻道
本文主要介紹關于MySQL默認值和約束的查詢方法,下面,我們一起來看。
一、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;
說明:
- database_name - 數據庫的名稱(模式)
- table_name - 表的名稱
- column_name - 列的名稱
- column_default - 定義此列默認值的 SQL 表達式
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;
說明:
- column_default -為沒有默認值的列定義默認約束(公式)和NULL
- tables- 具有此約束的表數(或具有對NULL行沒有約束的列的表數)
- columns - 具有此特定約束的列數(或NULL行沒有約束)
二、約束
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 子句中的條件并提供您的數據庫名稱。
說明:
- database_name - 數據庫的名稱(模式)
- table_name - 表的名稱
- column_id - 列在表中的位置
- column_name - 列的名稱
- data_type - 列數據類型
- max_length - 數據類型的最大長度
- precision- 數據類型的精度
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;
說明:
- database_name - 數據庫名稱(模式)
- table_name - 表名
- column_name - 列名
- nullable- 列的可空性屬性:is nullable- 可以為空,not nullable- 不可為空
責任編輯:趙寧寧
來源:
今日頭條