PostgreSQL 15中如何展示含外键关联的表结构(兼容PG14结果)
PostgreSQL 15 兼容版:查询表主键与外键关联关系
你的PG14查询在PG15失效的核心原因是PostgreSQL 15调整了information_schema.constraint_column_usage的收录规则——主键约束不再被该表收录(因为主键是当前表的约束,不存在外部引用),原查询的INNER JOIN会直接过滤掉所有主键记录,导致结果缺失。
以下是适配PG15的修改版查询,能生成和原语句完全一致格式的结果集:
SELECT DISTINCT tc.table_schema "sc", tc.table_name "tab1", kcu.column_name "columnname", tc.constraint_name "conname", CASE WHEN tc.constraint_type = 'FOREIGN KEY' THEN 'R' WHEN tc.constraint_type = 'PRIMARY KEY' THEN 'P' END AS constrainttype, kcu.ordinal_position "position", CASE WHEN tc.constraint_type = 'FOREIGN KEY' THEN ccu.table_schema END AS r_table_schema, CASE WHEN tc.constraint_type = 'FOREIGN KEY' THEN ccu.table_name END AS r_table_name, CASE WHEN tc.constraint_type = 'FOREIGN KEY' THEN ccu.column_name END AS r_column_name FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema LEFT JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema AND tc.constraint_type = 'FOREIGN KEY' -- 仅外键约束关联引用信息 WHERE tc.table_schema = 's1';
关键修改说明
- 将原有的
INNER JOIN constraint_column_usage改为LEFT JOIN,确保主键记录不会被过滤 - 在ccu的关联条件中增加
AND tc.constraint_type = 'FOREIGN KEY',仅为外键约束匹配引用的表/列信息 - 保留原有的CASE逻辑,保证主键记录的引用字段返回空值,外键记录返回正确关联信息
示例结果(与PG14格式一致)
| sc | tab1 | columnname | conname | constrainttype | position | r_table_schema | r_table_name | r_column_name |
|---|---|---|---|---|---|---|---|---|
| s1 | d1 | d1_key | d1_pk | P | 1 | |||
| s1 | d2 | denm_key | c_denm_d2 | R | 1 | s1 | denm | denm_key |
| s1 | d2 | d1_key | c_d1_d2 | R | 1 | s1 | d1 | d1_key |
| s1 | d2 | d2_key | d2_pk | P | 1 | |||
| s1 | d2 | vsubtype_key | c_vsubtype_d2 | R | 1 | s1 | vsubtype | vsubtype_key |
| s1 | d2 | vtype_key | c_vtype_d2 | R | 1 | s1 | vtype | vtype_key |
内容的提问来源于stack exchange,提问作者Erik Christiansen
相关产品推荐
相关产品推荐

