如何在没有主键的情况下列出所有表?

Phi*_*ord 10 postgresql primary-key information-schema

我已经看到大量查询来列出主键和外键,但是如何查询缺少主键的表?

a_h*_*ame 16

要列出没有主键的所有表,您可以使用:

select tbl.table_schema, 
       tbl.table_name
from information_schema.tables tbl
where table_type = 'BASE TABLE'
  and table_schema not in ('pg_catalog', 'information_schema')
  and not exists (select 1 
                  from information_schema.key_column_usage kcu
                  where kcu.table_name = tbl.table_name 
                    and kcu.table_schema = tbl.table_schema)
Run Code Online (Sandbox Code Playgroud)

我不清楚您是否要查找未引用任何其他表或其他表未引用的表的表。但是两者都可以通过information_schema.referential_constraints与上述查询类似的方式进行查询。


gra*_*emp 6

另一种查询获取所有没有主键的表:

SELECT table_schema || '.' || table_name
FROM information_schema.tables
WHERE
    (table_catalog, table_schema, table_name) NOT IN (
        SELECT table_catalog, table_schema, table_name
        FROM information_schema.table_constraints
        WHERE constraint_type = 'PRIMARY KEY') AND
    table_schema NOT IN ('information_schema', 'pg_catalog', 'pgq', 'londiste');
Run Code Online (Sandbox Code Playgroud)

不幸的是 PostgreSQL 不知道哪些表应该有 FK。所以这是手工工作,你需要检查所有的表并自己找到这样的表。

  • 接受的答案不起作用,这个答案起作用! (3认同)