简体   繁体   English

在完全外连接中获取不同的值

[英]Get distinct values in full outer join

I have two tables that have distinct ids我有两个具有不同 id 的表

Table 1    Table 2    Desired Result
+----+     +----+     +--------------------+
| id |     | id |  =  | id | a     | b     |
+----+     +----+     +--------------------+
| 1  |     | 2  |     | 1  | TRUE  | FALSE |
| 2  |     | 3  |     | 2  | TRUE  | TRUE  |
| 3  |     | 4  |     | 3  | TRUE  | TRUE  |
+----+     +----+     | 4  | FALSE | TRUE  |
                      +--------------------+

and I'm querying them like this:我像这样查询他们:

SELECT
  id,
  table1.id IS NOT NULL as a,
  table2.id IS NOT NULL as b,
FROM table1
FULL JOIN table2
  USING (id)

If id is unique in table1 and in table2 is it guarunteed to be unique in the resulting table?如果 id 在 table1 和 table2 中是唯一的,是否保证在结果表中是唯一的? Is there a better way to get my desired result, or is the best way?有没有更好的方法来获得我想要的结果,或者是最好的方法?

i would try this option我会试试这个选项

  select id
       ,max(case when a is null then 'FALSE' else 'TRUE' end) as a
       ,max(case when b is null then 'FALSE' else 'TRUE' end) as b
  from (
         select id,'TRUE' as a,null as b
           from table1
         union all
         select id,null as a,'TRUE' as b
           from table2
        )x
group by x.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM