2

我正在使用 Postgres 的元数据表(系统目录)构建查询,以获取我需要的一些信息。pg_constraint目录有一个名为conkeywhich is of type的列int2[],它引用。pg_attribute.attnum

我的问题不是关于系统目录本身,而是关于如何将这个int2[]数组扩展为一个实际列名的数组。例如:

a) pg_constraint:
conname | conrelid | conkey
const1  | 123      | {2, 3}

b) pg_class:
oid | relname
123 | table1

c) pg_attribute:
attrelid | attname | attnum
123      | colA    | 1
123      | colB    | 2
123      | colC    | 3

如何获得const_columns如下预期结果?

pseudo-query:
select b.relname as table, a.conname as constraint,
    /******> a.conkey expanded to c.attname <******/ as const_columns
    from pg_constraint a, pg_class b, pg_attribute c
    where a.conrelid = b.oid
    and c.attrelid = b.oid
    and a.conkey = c.attnum;

expected result:
table  | constraint | const_columns
table1 | const1     | {colB, colC}
4

1 回答 1

4
select
    b.relname as table,
    a.conname as constraint,
    array_agg(c.attname) as const_columns
from pg_constraint a, pg_class b, pg_attribute c
where
    a.conrelid = b.oid
    and c.attrelid = b.oid
    and c.attnum in (select unnest(a.conkey))
group by b.relname, a.conname

或使用数组运算符:

    and array[c.attnum] <@ a.conkey
于 2013-07-13T10:28:50.533 回答