在Postgres中包含架构信息的主键

时间:2018-04-05 22:15:34

标签: sql postgresql primary-key

我有这个问题:

SELECT column_name, data_type, character_maximum_length 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE table_name='my_table';

它的输出类似于:

              column_name               |    data_type     | character_maximum_length 
----------------------------------------+------------------+--------------------------
 key                                    | integer          |                         
 created_date_key                       | integer          |                         
 call_scheduled_date_key                | integer          |                         
 call_completed_date_key                | integer          |                         
 enroll_date_key                        | integer          |                         
 syllabus_request_date_fst_key          | integer          |                         
 info_session_registration_date_fst_key | integer          |                         

我想再增加两个列,一个名为" primary_key"另一个名为" foreign_key"包含布尔值。

这可能吗?

2 个答案:

答案 0 :(得分:2)

您可以从以下两种观看中获取此信息:key_column_usagereferential_constraintskey_column_usage视图列出了所有关键列:主要列和外键列。要区分这两者,请使用referential_constraints视图来告诉您约束是否是引用(外键)约束:

SELECT c.column_name, c.data_type, c.character_maximum_length,
CASE WHEN EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.constraint_column_usage k WHERE c.table_name = k.table_name and k.column_name = c.column_name) 
     THEN true ELSE false END as primary_key, 
CASE WHEN EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.key_column_usage k WHERE c.table_name = k.table_name and k.column_name = c.column_name) AND 
          EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.referential_constraints f INNER JOIN INFORMATION_SCHEMA.key_column_usage k ON k.constraint_name = f.constraint_name WHERE k.column_name = c.column_name) 
     THEN true ELSE false END as foreign_key 
FROM INFORMATION_SCHEMA.COLUMNS c 
WHERE c.table_name='my_table';

答案 1 :(得分:2)

您可以使用系统目录pg_constraint来获取所需的数据。例如:

create table my_table(
    id serial primary key, 
    fid int references my_other_table(id), 
    str varchar(10));

select 
    column_name, data_type, character_maximum_length, 
    bool_or(contype is not distinct from 'p') as primary_key, 
    bool_or(contype is not distinct from 'f') as foreign_key
from information_schema.columns
left join pg_constraint 
    on conrelid = table_name::regclass and ordinal_position = any(conkey)
where table_name='my_table'
group by 1, 2, 3;

 column_name |     data_type     | character_maximum_length | primary_key | foreign_key 
-------------+-------------------+--------------------------+-------------+-------------
 id          | integer           |                          | t           | f
 fid         | integer           |                          | f           | t
 str         | character varying |                       10 | f           | f
(3 rows)