我是PostgreSQL的新手,我想知道是否有一个与Oracle的user_cons_columns表匹配的表,该表提供类似于 user_cons_columns.position 的列位置列。本质上,我正在尝试将以下oracle代码转换为PostgreSQL。它按PK定义的顺序到达PK列:
select a.table_name tab_name,
a.colum_name col_name,
a.position col_order
from user_cons_columns a,
user_constraints b
where a.table_name = b.table_name
and a.constraint_name = b.constraint_name
and b.constraint_type = 'P'
and a.table_name = 'some_table_name';
/* Below is my attempt at the PostgreSQL conversion */
select isc.table_name tab_name,
isc.column_name col_name,
isc.ordinal_position col_order
from pg_attribute as pga
inner join pg_class as pgc on pga.attrelid = pgc.oid
inner join pg_namespace as pgn on pgn.oid = pgc.relnamespace
inner join information_schema.columns as isc on isc.column_name = pga.attname
and isc.table_name = pgc.relname
where isc.table_name = 'sometablename';
在我的PostgreSQL转换尝试中,我缺少约束与其位置之间的关系,但使用列位置。哪个不一样。有没有办法做前者?提前致谢!
答案 0 :(得分:1)
约束的列号及其顺序存储在pg_constraint.conkey
中;对于外键,目标列的相应编号在pg_constraint.confkey
中。
表列的描述在pg_attribute
中;列号存储在attnum
中。
答案 1 :(得分:1)
下面是由于@Laurenz Albe的回答而得出的解决方案。
select isc.table_name tab_name,
isc.col_name col_name,
pgco.conkey[1] col_order
from pg_attribute as pga
inner join pg_class as pgc on pga.attrelid = pgc.oid
inner join pg_namespace as pgn on pgn.oid = pgc.relnamespace
inner join information_schema.columns as isc on isc.column = pga.attname
and isc.table_name = pgc.relname
inner join pg_constraint as pgco on pgco.conkey[1] = pga.attnum
and pgco.connamespace = pgc.relnamespace
and pgco.conrelid = pga.attrelid
where isc.table_name = 'sometablename'
and pgco.contype ='p';
希望这对其他人有用。