PostgreSQL 15:查找public schema中无索引的外键列
查找public schema中外键未关联索引的列
以下是适用于PostgreSQL 15的查询语句,可直接返回public schema内所有作为外键但未对应索引的表名与列名:
SELECT tc.table_name AS 表名, kcu.column_name AS 外键列名 FROM information_schema.table_constraints AS tc JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name LEFT JOIN pg_index AS idx ON idx.indrelid = (tc.table_schema || '.' || tc.table_name)::regclass AND idx.indkey @> ARRAY[kcu.ordinal_position] WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public' AND idx.indexrelid IS NULL;
语句说明
- 通过
information_schema系统视图获取外键约束及关联列的基础信息 - 关联
pg_index系统表检查外键列是否存在对应索引:idx.indkey @> ARRAY[kcu.ordinal_position]用于判断目标列是否被包含在索引中 - 过滤条件限定为
publicschema下的外键,同时排除已存在索引的条目
内容的提问来源于stack exchange,提问作者Dawid
相关产品推荐
相关产品推荐

