如何在单个POSTGRESQL查询中获取列名及其引用类型(即PRIMARY KEY& FOREIGN KEY)?

时间:2017-08-22 11:38:26

标签: sql postgresql information-schema

我提出了以下查询,该查询为我提供了列名及其数据类型,但没有提供引用类型(即列是否为primary_key或foreign_key)。

select column_name, data_type,character_maximum_length,is_nullable
from   information_schema.columns
where  table_name ='employee';

这是我得到的输出:

 column_name |     data_type     | character_maximum_length | is_nullable
-------------+-------------------+--------------------------+-------------
 empno       | character varying |                       10 | NO
 full_name   | character varying |                       30 | YES
 city        | character varying |                        9 | YES
 gender      | character         |                        7 | YES

有人可以帮助我获取reference_type(即 PRIMARY_KEY & FOREIGN_KEY )以及查询吗?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

 select c.column_name, c.data_type, c.character_maximum_length, c.is_nullable, s.constraint_name, t.constraint_type
    from   information_schema.columns c
    left join information_schema.key_column_usage s on s.table_name = c.table_name and s.column_name = c.column_name
    left join information_schema.table_constraints t on t.table_name = c.table_name and t.constraint_name = s.constraint_name
    where  c.table_name ='employee'

看一下这个链接 https://www.postgresql.org/docs/9.1/static/information-schema.html