Postgresql 在Postgres中获取引用表
我有一个外键列表。我想找出这些FK指向的表和实际的键指向的表 我有一张FK的清单,像这样:Postgresql 在Postgres中获取引用表,postgresql,knex.js,Postgresql,Knex.js,我有一个外键列表。我想找出这些FK指向的表和实际的键指向的表 我有一张FK的清单,像这样: columnName0, columnName1, columnName2 外键引用 columnName0referencestable0.idTable0 columnName1referencestable1.idTable1 columnName2referencestable2.idTable2 一些示例表: 表0: idTable0, PK name idTable1, PK age
columnName0, columnName1, columnName2
外键引用
referencescolumnName0
table0.idTable0
referencescolumnName1
table1.idTable1
referencescolumnName2
table2.idTable2
idTable0, PK
name
idTable1, PK
age
idTable2, PK
createdOn
表1:
idTable0, PK
name
idTable1, PK
age
idTable2, PK
createdOn
表2:
idTable0, PK
name
idTable1, PK
age
idTable2, PK
createdOn
示例结果:
| column | referenced_column | referenced_table |
|-------------|-------------------|------------------|
| columnName0 | idTable0 | table0 |
| columnName1 | idTable1 | table1 |
| columnName2 | idTable2 | table2 |
我正在尝试将我在MySQL中所做的事情翻译为:
SELECT DISTINCT
COLUMN_NAME AS column,
REFERENCED_COLUMN_NAME AS referenced_column,
REFERENCED_TABLE_NAME AS referenced_table
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
COLUMN_NAME IN (?);
...
select conname, conrelid::regclass, confrelid::regclass, col, fcol
from pg_constraint c,
lateral unnest(conkey, confkey) u(col, fcol)
where contype = 'f' -- foreign keys constraints
...
我将不得不使用直接查询(不幸的是,没有存储过程)。您可以查询。对于列名,您应该查找。外键可以基于多列,因此pg_constraint
的conkey
和confkey
是数组。您必须取消数组的测试以获得列名列表。例如:
select
conrelid::regclass table_name,
a1.attname column_name,
confrelid::regclass referenced_table,
a2.attname referenced_column,
conname constraint_name
from (
select conname, conrelid::regclass, confrelid::regclass, col, fcol
from pg_constraint c,
lateral unnest(conkey) col,
lateral unnest(confkey) fcol
where contype = 'f' -- foreign keys constraints
) s
join pg_attribute a1 on a1.attrelid = conrelid and a1.attnum = col
join pg_attribute a2 on a2.attrelid = confrelid and a2.attnum = fcol;
table_name | column_name | referenced_table | referenced_column | constraint_name
------------+-------------+------------------+-------------------+------------------------
products | image_id | images | id | products_image_id_fkey
(1 row)
在Postgres 9.4或更高版本中,函数
unnest()
可能有多个参数,内部查询可能如下所示:
SELECT DISTINCT
COLUMN_NAME AS column,
REFERENCED_COLUMN_NAME AS referenced_column,
REFERENCED_TABLE_NAME AS referenced_table
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
COLUMN_NAME IN (?);
...
select conname, conrelid::regclass, confrelid::regclass, col, fcol
from pg_constraint c,
lateral unnest(conkey, confkey) u(col, fcol)
where contype = 'f' -- foreign keys constraints
...
@MikeSherrill'CatRecall'-是的,是的,看到了吗