2010-04-21 61 views
32

我有一個擁有超過150個表格的大型數據庫,最近我已交給他們。我只是想知道是否有一種簡單的方法來查看整個數據庫而不是每個表的所有外鍵約束。查看整個MySQL數據庫的所有外鍵約束條件

+0

見劉德華的答案在這裏:https://stackoverflow.com/questions/201621/how-do-i-see-所有的外鍵到列表或列 – omarjebari 2017-08-09 18:32:42

回答

53

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

像這樣的東西應該這樣做:

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

看起來像那正是我所需要的。謝謝! – 2010-04-21 15:58:25

+1

有沒有什麼辦法可以實際列出外鍵的字段名? – JoeTidee 2015-08-18 08:47:30

5

用戶RedFilter目前公認的答案將正常工作,如果你只有1個數據庫,但如果你有很多。

進入use information_schema;使用該查詢來獲取外鍵name_of_db後:

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

使用此查詢來獲取保存到世界可寫文件output_filepath_and_namename_of_db外鍵:

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 '"'; 
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   | 
+----------------------------+--------------+---------------------+ 
1

查詢此代碼

select constraint_name, 
    table_schema, 
    table_name 
from information_schema.table_constraints 

你會得到constraint_name,並過濾TABLE_SCHEMA這是database列表。

Look at This

6

這是我喜歡得到有用的信息:

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'