How do I see all foreign keys to a table or column?

后端 未结 13 986
忘了有多久
忘了有多久 2020-11-22 09:14

In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as this Oracle question, but for MyS

13条回答
  •  独厮守ぢ
    2020-11-22 09:39

    Posting on an old answer to add some useful information.

    I had a similar problem, but I also wanted to see the CONSTRAINT_TYPE along with the REFERENCED table and column names. So,

    1. To see all FKs in your table:

      USE '';
      
      SELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
      FROM information_schema.TABLE_CONSTRAINTS i 
      LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
      WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' 
      AND i.TABLE_SCHEMA = DATABASE()
      AND i.TABLE_NAME = '';
      
    2. To see all the tables and FKs in your schema:

      USE '';
      
      SELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
      FROM information_schema.TABLE_CONSTRAINTS i 
      LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
      WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' 
      AND i.TABLE_SCHEMA = DATABASE();
      
    3. To see all the FKs in your database:

      SELECT i.TABLE_SCHEMA, i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
      FROM information_schema.TABLE_CONSTRAINTS i 
      LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
      WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY';
      

    Remember!

    This is using the InnoDB storage engine. If you can't seem to get any foreign keys to show up after adding them it's probably because your tables are using MyISAM.

    To check:

    SELECT * TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = '';
    

    To fix, use this:

    ALTER TABLE `` ENGINE=InnoDB;
    

提交回复
热议问题