在Postgres查询中获取子表名

时间:2017-10-23 00:44:29

标签: sql postgresql

我有一个基表

CREATE TABLE base_table (
  id SERIAL PRIMARY KEY
);

从中继承的两个子表

CREATE TABLE child_a (
  description TEXT
) INHERITS (base_table);

CREATE TABLE child_b (
  age INT
) INHERITS (base_table);

我正在尝试编写一个查询,该查询将返回基表及其所有子项中的所有字段,但还会附加每行的父级' s'表格结果。

到目前为止,我可以通过

获得我需要的所有其他字段
SELECT id, description, age
FROM ONLY base_table
NATURAL FULL JOIN child_a
NATURAL FULL JOIN child_b

我对如何在结果中包含父表名有点困惑。我希望结果像是

Id, Description,      Age,   TableName
---------------------------------------
1   TestDescription   null   child_a
2   null              10     child_b
3   OtherDescription  null   child_a

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

使用子查询而不是子表:

SELECT id, description, age, coalesce(t1, t2) as tablename
FROM base_table
NATURAL FULL JOIN (
    SELECT *, 'child_a'::text AS t1
    FROM child_a
    ) a
NATURAL FULL JOIN (
    SELECT *, 'child_b'::text AS t2
    FROM child_b
    ) b;

 id |   description    | age | tablename 
----+------------------+-----+-----------
  1 | TestDescription  |     | child_a
  2 |                  |  10 | child_b
  3 | OtherDescription |     | child_a
(3 rows)    

更新。有一个很好的解决方案in ths answer。要在这种情况下使用它,您必须明确指定system column tableoid:

的base_table
SELECT *, base_table.tableoid::regclass::text AS table_name
FROM base_table
FULL JOIN child_a USING(id)
FULL JOIN child_b USING(id);