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;
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;
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;
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;
这是更准确的答案:
您错过了该
and kc.constraint_name = tc.constraint_name
部分,因此它列出了所有约束。像这样的东西:
也请考虑这一点。这将生成脚本以更改所有表。
我认为获取主键和外键应该这样做。kc.position_in_unique_constraint 不为空这个条件可能只获取外键。