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)
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');
SELECT pgc.relname
FROM pg_class pgc
JOIN pg_namespace pgns ON pgns.oid = pgc.relnamespace
WHERE pgns.nspname = 'public'
AND pgc.relkind = 'r'
AND pgc.oid NOT IN
(SELECT pgc.oid
FROM pg_class pgc
JOIN pg_index pgi ON pgi.indrelid = pgc.oid
JOIN pg_namespace pgns ON pgns.oid = pgc.relnamespace
WHERE pgi.indisprimary = true
AND pgc.relkind = 'r'
AND pgns.nspname = 'public'
);
SELECT table_name
FROM information_schema.tables
WHERE table_name NOT IN (
SELECT distinct table_name
FROM information_schema.table_constraints
WHERE constraint_type = 'FOREIGN KEY' and table_schema ='xxxxx') AND
table_schema ='xxxxx'
要列出所有没有主键的表,可以使用:
我不清楚您是否要查找未引用任何其他表或其他表未引用的表的表。但是这两件事都可以通过
information_schema.referential_constraints
与上述查询类似的方式进行查询。获取所有没有主键的表的另一个查询:
不幸的是,PostgreSQL 不知道哪些表应该有 FK。所以这是手工工作,您需要查看所有表格并自己找到这些表格。
我对@a_horse_with_no_name 的回答有疑问,这对我来说错过了表格。由于某种原因,grayhemp 的返回视图并在我们的生产环境中给了我完全错误的结果。
我从头开始编写此查询,查询特定于 Postgres 的表,例如
pg_class
. 一般来说,我发现查询这些表也更快(我假设因为这些information_schema
表实际上是大量视图),如果您在测试中运行这种查询,这很好。这是对 FK 的查询。