简体   繁体   中英

Get all the column names having a Foreign Key contraint

I am using the PostgreSQL. I want to write a query that returns all the column names having foreign key constraint and also the name of the table these columns they refer to.

As far as I can see, the information_schema views don't give you the column names, so you'll have to use the catalog:

SELECT c.conrelid::regclass AS source_table,
       a.attname AS column_name,
       k.n AS position,
       c.confrelid::regclass AS referenced_table
FROM pg_constraint AS c
   CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, n)
   JOIN pg_attribute AS a
      ON k.attnum = a.attnum AND c.conrelid = a.attrelid
WHERE c.contype = 'f'
ORDER BY c.conrelid::regclass::text, k.n;

To get the data for only a specific table, add the following to the WHERE condition:

AND c.conrelid = 'mytable'::regclass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM