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

Wil*_*her 0 sql sql-server

我有以下表格结构

表格1:

+--------+
| foo_id |
+--------+
|      1 |
|      2 |
|      3 |
+--------+
Run Code Online (Sandbox Code Playgroud)

表2:

+--------+--------+
| foo_id | bar_id |
+--------+--------+
|      1 |      1 |
|      1 |      2 |
|      1 |      3 |
|      3 |      2 |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

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

+--------+--------+
| foo_id | bar_id |
+--------+--------+
|      1 | 1      |
|      2 | null   |
|      3 | null   |
+--------+--------+
Run Code Online (Sandbox Code Playgroud)

我想到了什么......

select table2.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
                       and table2.bar_id = 1
Run Code Online (Sandbox Code Playgroud)

但它不太有效,我为foo_id = 1获得3行.

有任何想法吗?

非常感谢!

小智 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
Run Code Online (Sandbox Code Playgroud)

select table1.foo_id, table2.bar_id 
from table1
left join table2    on table1.foo_id = table2.foo_id
                       and table2.bar_id = 1
Run Code Online (Sandbox Code Playgroud)

你错误地选择了错误的表来输出foo_id