简体   繁体   中英

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

I have the following table structure

Table1:

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

Table2:

+--------+--------+
| 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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