如何在Postgre中返回主列名称?

时间:2019-04-03 23:35:33

标签: sql postgresql knex.js

我正在为KnexJS进行包装,并且为了使错误更具描述性,我希望能够获得表的主列的名称。我看过了,但是找不到任何答案。我不擅长SQL,因此如果它是高级的,请尝试将其分解。

1 个答案:

答案 0 :(得分:0)

要找出给定表上PK的PK名称和列名称:

SELECT t.relname AS table_name
     , i.relname AS index_name
     , ia.attname AS column_name
  FROM pg_class t
  JOIN pg_index ix
    ON ix.indrelid = t.oid
   AND ix.indisprimary = 't'
  JOIN pg_class i
    ON i.oid = ix.indexrelid
  JOIN pg_attribute ia 
    ON ia.attrelid = t.oid
   AND ia.attnum = ANY(ix.indkey)
 WHERE t.relkind = 'r' -- table
   AND t.relname = 'your_table_name'

请注意,对于复合PK(多列),它将在单独的行中列出它们。如果要每个表一行,只需GROUP BY t.relname, i.relname,然后选择array_to_string(array_agg(ia.attname), ', ') as columns