简体   繁体   English

如何联接表:列等于值还是null?

[英]How to join tables: Column equals value or is null?

I have the following table structure 我有以下表格结构

Table1: 表格1:

+--------+
| foo_id |
+--------+
|      1 |
|      2 |
|      3 |
+--------+

Table2: 表2:

+--------+--------+
| foo_id | bar_id |
+--------+--------+
|      1 |      1 |
|      1 |      2 |
|      1 |      3 |
|      3 |      2 |
+--------+--------+

Now, I want an output like this: 现在,我想要这样的输出:

+--------+--------+
| foo_id | bar_id |
+--------+--------+
|      1 | 1      |
|      2 | null   |
|      3 | null   |
+--------+--------+

What came to my mind was sth like 我想到的是

select table2.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
                       and table2.bar_id = 1

but it does not quite work, I get 3 lines for foo_id = 1. 但是它不能正常工作,对于foo_id = 1我得到3行。

Any ideas? 有任何想法吗?

Thanks very much! 非常感谢!

You only need to change from: 您只需更改以下内容:

select table2.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
                       and table2.bar_id = 1

to

select table1.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
                       and table2.bar_id = 1

You mistakenly chose the wrong table to output foo_id from 您错误地选择了错误的表来输出foo_id

select table2.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
where table2.bar_id = 1 or table2.bar_id is null

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

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