Gibt es eine Abfrage, die das macht?
Ich habe einige Abfragen gefunden, die dies für eine Tabelle tun können, konnte sie jedoch nicht ändern, sodass ich Folgendes sehen kann:
tablename | column | type
Etwas wie das:
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;
Dies ist eine genauere Antwort:
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;
Du hast das and kc.constraint_name = tc.constraint_name
Teil, so dass alle Einschränkungen aufgelistet werden.
Ich denke, Primärschlüssel und Fremdschlüssel sollten so funktionieren. kc.position_in_unique_constraint ist nicht null. Diese Bedingung kann nur Fremdschlüssel erhalten.
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;
Bitte beachten Sie dies auch. Dadurch wird das Skript zum Ändern aller Tabellen generiert.
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;