显示Postgresql中某些表的约束

时间:2018-06-14 22:37:09

标签: postgresql

我想知道如何通过PostgreSQL中的SELECT语句显示某个表(所有列)的所有约束。我试过这段代码:

SELECT * FROM information_schema.table_constraints;
SELECT * FROM information_schema.referential_constraints;

实际上,我想要表格的主键和外键

1 个答案:

答案 0 :(得分:0)

以下应该做的伎俩。只需使用您的表名更改 table-name-goes-here

SELECT
    tc.table_schema, 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 
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
WHERE constraint_type in ('PRIMARY KEY', 'FOREIGN KEY') 
AND tc.table_name='table-name-goes-here';