[英]How to join tables: Column equals value or is null?
我有以下表格結構
表格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行。
有任何想法嗎?
非常感謝!
您只需更改以下內容:
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
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.