MySQL数据库的约束列表


Answers:


141

使用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'

1
该列表将仅包括UNIQUE,PRIMARY KEY或FOREIGN KEY约束。可以检查,但不强制执行。使用此查询将不显示DEFAULT约束。
OMG小马

MySQL不存储CHECK约束。如果尝试定义一个,它将解析并静默丢弃它。
Bill Karwin 2010年

1
DEFAULT值不算作约束。它存储在中information_schema.columns.column_default
Bill Karwin 2010年

22

@Senseful的很好答案。

我为那些只在查找约束名称列表(而不是其他详细信息/列)的人员提供了修改后的查询:

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

2
如果您需要找到一个就删除它,请参见此处stackoverflow.com/a/838412/2401804
r3wt

9

如果您想查看主键和外键约束以及围绕这些约束的规则(如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”;


1
据我所知,这是在Oracle中,而不是MySQL中。
Pradyumn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.