列出所有表的主键 - Postgresql

kor*_*rda 19 schema postgresql

是否有一个查询可以做到这一点?

我发现了一些可以对一张表执行此操作的查询,但我无法对其进行修改,因此我可以看到:

tablename | column | type
Run Code Online (Sandbox Code Playgroud)

小智 22

这是更准确的答案:

select tc.table_schema, tc.table_name, kc.column_name 
from  
    information_schema.table_constraints tc,  
    information_schema.key_column_usage kc  
where 
    tc.constraint_type = 'PRIMARY KEY' 
    and kc.table_name = tc.table_name and kc.table_schema = tc.table_schema
    and kc.constraint_name = tc.constraint_name
order by 1, 2;
Run Code Online (Sandbox Code Playgroud)

您错过了该and kc.constraint_name = tc.constraint_name部分,因此它列出了所有约束条件。

  • 虽然您的查询有效,但更重要的区别是缺少 `and kc.position_in_unique_constraint is not null` 部分。并且强烈建议您使用 ANSI JOIN(虽然许多人认为这是一个品味问题)。 (2认同)

a_h*_*ame 14

像这样的东西:

select tc.table_schema, tc.table_name, kc.column_name
from information_schema.table_constraints tc
  join information_schema.key_column_usage kc 
    on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name
where tc.constraint_type = 'PRIMARY KEY'
  and kc.ordinal_position is not null
order by tc.table_schema,
         tc.table_name,
         kc.position_in_unique_constraint;
Run Code Online (Sandbox Code Playgroud)

  • @a_horse_with_no_name 我相信这是不正确的。`position_in_unique_constraint` 表示 FOREIGN 键的位置,主键始终为 null。正确的列是“ordinal_position”。在 PG 9.4 中测试。 (2认同)