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

获取复合外键关联表依赖及字段顺序的正确SQL查询方法

Got it, I get why your current query isn't working right for composite foreign keys—PostgreSQL keeps track of the exact order those columns were defined in, and your original query isn't respecting that order. Tools like PgAdmin use the ordinal position metadata to show constraints correctly, so we just need to tweak your query to do the same.

Fixing Composite Foreign Key Column Order in PostgreSQL

The core issue here is that composite foreign keys have a defined column sequence, and your existing query doesn't account for the ordinal_position field that PostgreSQL uses to store this order. Here's the corrected query that matches what you see in PgAdmin:

SELECT
    tc.constraint_name AS nom_fk,
    tc.table_name AS table_out,
    kcu.column_name AS colonne_out,
    ccu.table_name AS table_in,
    ccu.column_name AS colonne_in,
    kcu.ordinal_position AS fk_column_order -- Optional, but useful to verify order
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
JOIN
    information_schema.constraint_column_usage AS ccu
    ON kcu.constraint_name = ccu.constraint_name
    AND kcu.table_schema = ccu.table_schema
    AND kcu.ordinal_position = ccu.ordinal_position -- Critical for matching column order
WHERE
    tc.constraint_type = 'FOREIGN KEY'
ORDER BY
    tc.table_name,
    tc.constraint_name,
    kcu.ordinal_position; -- Ensures columns appear in their defined order

What Changed & Why:

  • Added kcu.ordinal_position = ccu.ordinal_position to the join: This ensures each foreign key column maps to the correct referenced column in the exact sequence they were created. Without this, composite FK columns might be mismatched or out of order.
  • Ordered results by ordinal_position: Groups all columns for a single composite FK together and displays them in their defined order, just like PgAdmin does.
  • Included fk_column_order (optional): This column makes it easy to confirm the sequence is correct at a glance.

Example of Correct Output:

If you have a composite FK fk_order_details (order_id, product_id) referencing orders(id, product_id), the query will return rows in this order:

nom_fktable_outcolonne_outtable_incolonne_infk_column_order
fk_order_detailsorder_itemsorder_idordersid1
fk_order_detailsorder_itemsproduct_idordersproduct_id2

This is exactly the structure you'd see when viewing the constraint in PgAdmin.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:20:49