开发者

sql lists out all foreign keys of a primary key

Let's say the "user_id" field on "table_users" is primary key for 10 foreign keys on 10 other tables. I want to rename the field of primary key on "table_users", but it doesn't allow me to rename it be开发者_StackOverflow社区cause there are 10 foreign keys from 10 other tables are linked to it. May I know how to know which of the 10 tables has the foreign keys? What is the sql code to show the 10 tables which has the foreign keys?

I am using phpMyAdmin and InnoDB engine. I know SHOW ENGINE INNODB STATUS can do the job but it show me 1 table for each time, mean I need to repeat rename the primary key field for 10 times and run SHOW ENGINE INNODB STATUS for 10 times to find out all the 10 tables. Is there any other better solution to find out the 10 tables?


You can try querying INFORMATION_SCHEMA database:

select ku.* 
from INFORMATION_SCHEMA.table_constraints tc   
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku ON
(tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME and tc.CONSTRAINT_SCHEMA =   
ku.CONSTRAINT_SCHEMA )
where constraint_type='FOREIGN KEY' and ku.REFERENCED_TABLE_NAME =     
'your_table_name'


As the mysql root user, you can get around this issue using

SET foreign_key_checks = 0;

This disables the constraint system and will allow you to alter your table definition. Of course from there all your foreign key constraints will be broken, and need to be dropped and recreated.

SET foreign_key_checks = 1;

Will turn the constraint system back on.

Mysql also has a data dictionary that can be queried. That was covered fully in This previous question so I'm not going to repeat any of that info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜