用union连接两个表

时间:2016-04-25 14:09:00

标签: postgresql

将PostgreSQL版本9.5.1中的两个表与UNION连接起来;并检查列name中的值是否出现在这些表中的一个或两个中,并带有布尔值。

这是我的最小示例代码:

WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT *
FROM
  (SELECT name AS name,
      TRUE AS in_a,
          NULL::boolean AS in_b
   FROM things_a
   UNION SELECT name AS name,
        NULL AS in_a,
        TRUE AS in_b
   FROM things_b) AS things
ORDER BY name

我希望得到以下结果:

name   | in_a    | in_b
------------------------
AAA    | t       | f
BBB    | t       | t
CCC    | t       | t
DDD    | f       | t

但是当然可能有另一种方法

1 个答案:

答案 0 :(得分:0)

您真的想使用UNION吗?

你可以简单地使用:

WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT COALESCE(things_a.name,things_b.name) as name,
       things_a.name is not null as in_a, 
       things_b.name is not null as in_b
from things_a full outer join things_b 
     on things_a.name=things_b.name
order by 1
;

或者您的隐含问题是否要求提供示例代码中缺少的部分?

以下可能是您正在寻找的内容:

WITH things_a(name) AS (
            VALUES ('AAA'),('BBB'),('CCC')),
     things_b(name) AS (
            VALUES ('BBB'),('CCC'),('DDD'))
SELECT name, COALESCE(bool_or(in_a),false) as in_a, coalesce(bool_or(in_b),false) in_b
FROM
  (SELECT name AS name,
      TRUE AS in_a,
          NULL::boolean AS in_b
   FROM things_a
   UNION SELECT name AS name,
        NULL AS in_a,
        TRUE AS in_b
   FROM things_b) AS things
group by name
ORDER BY name;