List of Constraints from MySQL Database

前端 未结 4 757
猫巷女王i
猫巷女王i 2020-12-02 05:37

How do I get a list of all constraints from a particular database?

相关标签:
4条回答
  • 2020-12-02 05:54

    SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";

    0 讨论(0)
  • 2020-12-02 06:14

    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;
    
    0 讨论(0)
  • 2020-12-02 06:15

    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'
    
    0 讨论(0)
  • 2020-12-02 06:20

    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
    
    0 讨论(0)
提交回复
热议问题