2017-05-30 52 views
1

我有一些PK表,這些表都是從專用序列中獲取的。不幸的是,我想這些序列中的一個被用於兩個不同的表格(用於生成一個ID)。是否可以編寫一個將返回所有字段的查詢(字段名稱始終爲ID),並使用爲這些字段生成默認值的序列?如何將ID字段與其序列進行匹配?

回答

2

查詢列出表名與表的id列相關序列:

select 
    nspname as schema, 
    relname as table, 
    trim(substring(pg_get_expr(adbin, adrelid), e'\'.*\''), '''') as sequence 
from pg_attribute a 
join pg_attrdef d on adrelid = attrelid and adnum = attnum 
join pg_class c on c.oid = attrelid 
join pg_namespace n on n.oid = relnamespace 
where attname = 'id' and atthasdef 
and left(pg_get_expr(adbin, adrelid), 7) = 'nextval'; 

schema | table  |  sequence  
--------+--------------+--------------------- 
public | test_table | test_table_id_seq 
public | log   | log_id_seq 
public | master  | master_id_seq 
public | details  | details_id_seq 
... 

可以跳過條件attname = 'id'。該查詢查找具有作爲默認表達式的函數nextval()的列,例如:

select 
    nspname as schema, 
    relname as table, 
    attname as column, 
    trim(substring(pg_get_expr(adbin, adrelid), e'\'.*\''), '''') as sequence 
from pg_attribute a 
join pg_attrdef d on adrelid = attrelid and adnum = attnum 
join pg_class c on c.oid = attrelid 
join pg_namespace n on n.oid = relnamespace 
where atthasdef 
and left(pg_get_expr(adbin, adrelid), 7) = 'nextval'; 

schema | table  | column |  sequence   
--------+--------------+-----------+----------------------- 
public | test_table | id  | test_table_id_seq 
public | log   | id  | log_id_seq 
public | wallets  | wallet_id | wallets_wallet_id_seq 
public | master  | id  | master_id_seq 
public | details  | id  | details_id_seq 
... 
相關問題