如何从特定数据库获取所有约束的列表?
Answers:
使用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'
information_schema.columns.column_default
。
@Senseful的很好答案。
我为那些只在查找约束名称列表(而不是其他详细信息/列)的人员提供了修改后的查询:
SELECT DISTINCT(constraint_name)
FROM information_schema.table_constraints
WHERE constraint_schema = 'YOUR_DB'
ORDER BY constraint_name ASC;
如果您想查看主键和外键约束以及围绕这些约束的规则(如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