2016-07-26 55 views
0

我有以下查詢返回外鍵的詳細信息:如何查詢外鍵onupdate/ondelete?

SELECT 
    tc.constraint_name, 
    tc.table_name, 
    kcu.column_name, 
    ccu.table_schema AS foreign_table_schema, 
    ccu.table_name AS foreign_table_name, 
    ccu.column_name AS foreign_column_name, 
    pg_catalog.pg_get_constraintdef(pg_constraint.oid, true) AS foreign_definition 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu 
     ON tc.constraint_name = kcu.constraint_name 
    JOIN information_schema.constraint_column_usage AS ccu 
     ON ccu.constraint_name = tc.constraint_name 
    JOIN pg_constraint 
     ON pg_constraint.conname = tc.constraint_name 
WHERE constraint_type = 'FOREIGN KEY' 

從這個,我可以得到大部分的我需要重新consturct的外鍵的信息。唯一缺少的是關於刪除信息的更新&(儘管這可以從foreign_definition解析出)。我一直在想方設法接收這些細節而不解析它,但到目前爲止我沒有運氣。

有沒有人有關於哪個表的詳細信息,我可以找到關於更新和刪除詳細信息?

這是專門爲Postgres。

+2

沒有嘗試'information_schema.referential_constraints'?..有兩列'update_rule'和'delete_rule' –

回答

2

這樣嗎?..

SELECT 
    tc.constraint_name, 
    tc.table_name, 
    kcu.column_name, 
    ccu.table_schema AS foreign_table_schema, 
    ccu.table_name AS foreign_table_name, 
    ccu.column_name AS foreign_column_name, 
    pg_catalog.pg_get_constraintdef(pg_constraint.oid, true) AS foreign_definition, 
    update_rule, 
    delete_rule 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu 
     ON tc.constraint_name = kcu.constraint_name 
    JOIN information_schema.constraint_column_usage AS ccu 
     ON ccu.constraint_name = tc.constraint_name 
    JOIN pg_constraint 
     ON pg_constraint.conname = tc.constraint_name 
    LEFT OUTER JOIN information_schema.referential_constraints rc on tc.constraint_name = rc.constraint_name and ccu.table_schema = rc.constraint_schema 

WHERE constraint_type = 'FOREIGN KEY'