MySQL数据库中的约束列表

问题描述 投票:75回答:4

如何从特定数据库中获取所有约束的列表?

mysql database-design constraints
4个回答
117
投票

使用information_schema.table_constraints表获取每个表上定义的约束的名称:

select *
from information_schema.table_constraints
where constraint_schema = 'YOUR_DB'

使用information_schema.key_column_usage表获取每个约束中的字段:

select *
from information_schema.key_column_usage
where constraint_schema = 'YOUR_DB'

如果您正在谈论外键约束,请使用information_schema.referential_constraints

select *
from information_schema.referential_constraints
where constraint_schema = 'YOUR_DB'

19
投票

@Senseful给出了很好的答案。

我正在为那些只寻找约束名列表(而不是其他细节/列)的人提出修改后的查询:

SELECT DISTINCT(constraint_name) 
FROM information_schema.table_constraints 
WHERE constraint_schema = 'YOUR_DB' 
ORDER BY constraint_name ASC;

3
投票

如果您希望查看主键和外键约束以及围绕这些约束的规则(例如ON_UPDATE和ON_DELETE以及列和外部列名称),这确实很有用:

SELECT tc.constraint_schema,tc.constraint_name,tc.table_name,tc.constraint_type,kcu.table_name,kcu.column_name,kcu.referenced_table_name,kcu.referenced_column_name,rc.update_rule,rc.delete_rule

FROM information_schema.table_constraints tc

inner JOIN information_schema.key_column_usage kcu
ON tc.constraint_catalog = kcu.constraint_catalog
AND tc.constraint_schema = kcu.constraint_schema
AND tc.constraint_name = kcu.constraint_name
AND tc.table_name = kcu.table_name

LEFT JOIN information_schema.referential_constraints rc
ON tc.constraint_catalog = rc.constraint_catalog
AND tc.constraint_schema = rc.constraint_schema
AND tc.constraint_name = rc.constraint_name
AND tc.table_name = rc.table_name

WHERE tc.constraint_schema = 'my_db_name'

您甚至可能希望添加有关这些列的更多信息,只需将其添加到SQL中(并选择所需的列):

LEFT JOIN information_schema.COLUMNS c
ON kcu.constraint_schema = c.table_schema
AND kcu.table_name = c.table_name
AND kcu.column_name = c.column_name

-3
投票

SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME =“tabnam”;

© www.soinside.com 2019 - 2024. All rights reserved.