You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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]用于判断目标列是否被包含在索引中
  • 过滤条件限定为public schema下的外键,同时排除已存在索引的条目

内容的提问来源于stack exchange,提问作者Dawid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 05:14:52