List of Constraints from MySQL Database
How do I get a lis开发者_如何学Got of all constraints from a particular database?
Use the information_schema.table_constraints
table to get the names of the constraints defined on each table:
select *
from information_schema.table_constraints
where constraint_schema = 'YOUR_DB'
Use the information_schema.key_column_usage
table to get the fields in each one of those constraints:
select *
from information_schema.key_column_usage
where constraint_schema = 'YOUR_DB'
If instead you are talking about foreign key constraints, use information_schema.referential_constraints
:
select *
from information_schema.referential_constraints
where constraint_schema = 'YOUR_DB'
Great answer by @Senseful.
I am presenting modified query for those who are only looking for list of constraint names (and not other details/columns):
SELECT DISTINCT(constraint_name)
FROM information_schema.table_constraints
WHERE constraint_schema = 'YOUR_DB'
ORDER BY constraint_name ASC;
This really helps if you want to see primary and foreign key constraints as well as rules around those constraints such as ON_UPDATE and ON_DELETE and the column and foreign column names all together:
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'
You may even want to add in some further information about those columns, simply add this into the SQL (and select the columns you want):
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
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";
精彩评论