如何连接表:列等于值或为空?

时间:2014-09-03 14:49:38

标签: sql sql-server

我有以下表结构

表1:

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

表2:

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

现在,我想要一个像这样的输出:

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

我想到的是......好像

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

但它不太有用,我为foo_id = 1获得3行。

有什么想法吗?

非常感谢!

2 个答案:

答案 0 :(得分:5)

您只需要更改:

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

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

您错误地选择了错误的表格从

输出foo_id

答案 1 :(得分:-1)

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