Answers:
像这样:
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;
tc.constraint_type = 'PRIMARY KEY'
将仅显示主键。然而,每个主键由唯一indexe支持
position_in_unique_constraint
指示FOREIGN键的位置,对于主键始终为null。正确的列是ordinal_position
。在PG 9.4中测试。
ordinal_position
应该使用。该position_in_unique_constraint
只FKS使用不为空。
这是更准确的答案:
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;
您错过了and kc.constraint_name = tc.constraint_name
零件,因此列出了所有约束。
and kc.position_in_unique_constraint is not null
部分。强烈建议您使用ANSI JOIN(虽然很多人认为这只是个问题)。
请也考虑这一点。这将生成用于更改所有表的脚本。
SELECT STRING_AGG(FORMAT('ALTER TABLE %s CLUSTER ON %s;', A.table_name, A.constraint_name), E'\n') AS SCRIPT
FROM
(
SELECT FORMAT('%s.%s', table_schema, table_name) AS table_name, constraint_name
FROM information_schema.table_constraints
WHERE UPPER(constraint_type) = 'PRIMARY KEY'
ORDER BY table_name
) AS A;
我认为获取主键和外键应该这样做。kc.position_in_unique_constraint不为null,此条件只能获取外键。
select tc.table_schema, tc.table_name, kc.column_name,tc.constraint_type
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
--kc.position_in_unique_constraint is not null
order by tc.table_schema,
tc.table_name,
kc.position_in_unique_constraint;