根据某种条件从多个 table 中读取列值 - postgreSQL

Reading a column value from more than one table based on some condition - postgreSQL

我正在尝试为我拥有的 table 之一创建一个视图。对于视图中的其中一列,我试图从我拥有的 tables 中读取值:

Table答:

id   b_id   c_id    d_id
1     1
2            1
3                     1

Table乙:

id   code
1     64

Table C:

id    code
1     98

Table D:

id     code
1       26

在上面的tables中,A是我的主table,它有两个外键引用tables B和C(b_id和c_id) 分别。对于 table A 中的每一行,只会填充两个引用(b_id 或 c_id)中的一个。

我的任务是为 table A 创建一个视图,比如 v_A,它将包含以下列:

查看v_A:

code      code_table
64           B
98           C
26           D

在上面的视图中,我必须首先检查 table A 中的每一行,填充了哪些外键引用,基于此我必须读取列 'code' 和'code_table' 列将具有我正在填充 'code' 列的 table 的名称。

我已经能够创建简单的视图,但这对我来说有点棘手。我正在检查我是否可以使用 case ...when 相同但在变得有点复杂之后。我还可以从 information_schema table 中读取 postgres 中的 table 名称。所以我有零碎的解决方案,但不明白如何将它们组合在一起。

有人能指出我正确的方向吗?

谢谢!!

当然,只有当您填写其中一个 table 或另一个时,它才会起作用 - 当两个故事都有匹配的键时,它不会解决冲突:

t=# create view _a as select coalesce(b.code,c.code,d.code) code, case when b.id is not null then 'B' when c.id is not null then 'C' when d.id is not null then 'D' end from a
left outer join b on b.id = b_id
left outer join c on c.id = c_id
left outer join d on d.id = d_id;
CREATE VIEW
t=# select * from _a;
 code | case
------+------
   26 | D
   98 | C
   64 | B
(3 rows)