查看整个MySQL数据库的所有外键约束

时间:2010-04-21 15:53:10

标签: mysql foreign-keys database

我有一个包含超过150个表的大型数据库,我最近已经提交过。我只是想知道是否有一种简单的方法来查看整个数据库的所有外键约束,而不是基于每个表。

5 个答案:

答案 0 :(得分:67)

您可以使用INFORMATION_SCHEMA表格。例如,INFORMATION_SCHEMA TABLE_CONSTRAINTS表。

这样的事情应该这样做:

select *
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_TYPE = 'FOREIGN KEY'

答案 1 :(得分:14)

这是我更喜欢获得有用的信息:

SELECT CONSTRAINT_NAME,
       UNIQUE_CONSTRAINT_NAME, 
       MATCH_OPTION, 
       UPDATE_RULE,
       DELETE_RULE,
       TABLE_NAME,
       REFERENCED_TABLE_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = 'your_database_name'

答案 2 :(得分:6)

如果您只有一个数据库,用户RedFilter当前接受的答案将正常工作,但如果您有很多数据库则不会。

输入use information_schema;后,使用此查询获取name_of_db的外键:

select * from `table_constraints` where `table_schema` like `name_of_db` and `constraint_type` = 'FOREIGN KEY'

使用此查询获取name_of_db保存到世界可写文件output_filepath_and_name的外键:

select * from `table_constraints` where `table_schema` like "name_of_db" and `constraint_type` = 'FOREIGN KEY' into outfile "output_filepath_and_name" FIELDS TERMINATED BY ',' ENCLOSED BY '"';

答案 3 :(得分:1)

查询此代码

select constraint_name,
   table_schema,
   table_name
from   information_schema.table_constraints

您将获得constraint_name,并过滤table_schema,它是database的列表。

Look at This

答案 4 :(得分:0)

<强> SQL:

select constraint_name,
       table_schema,
       table_name
from   information_schema.table_constraints
where  constraint_schema = 'astdb'

<强>输出:

+----------------------------+--------------+---------------------+
| constraint_name            | table_schema | table_name          |
+----------------------------+--------------+---------------------+
| PRIMARY                    | astdb        | asset_category      |
| PRIMARY                    | astdb        | asset_type          |
| PRIMARY                    | astdb        | asset_valuation     |
| PRIMARY                    | astdb        | assets              |
| PRIMARY                    | astdb        | com_mst             |
| PRIMARY                    | astdb        | com_typ             |
| PRIMARY                    | astdb        | ref_company_type    |
| PRIMARY                    | astdb        | supplier            |
| PRIMARY                    | astdb        | third_party_company |
| third_party_company_ibfk_1 | astdb        | third_party_company |
| PRIMARY                    | astdb        | user                |
| PRIMARY                    | astdb        | user_role           |
+----------------------------+--------------+---------------------+