简体   繁体   中英

MySQL: JOIN table B but return table A if no matches in table B

This is an abstraction of a problem I have. I have two tables:

id  name
--  ------
1   Frank
2   Tom

id  bar  drink
--  ---  -----
1    5   water
1    5   beer
1    6   wine
2    5   milk

I want to select id 1, bar 5 and get Frank and all his drinks at the bar 5.

id: 1, name: Frank, bar: 5, drink: water
id: 1, name: Frank, bar: 5, drink: beer
id: 1, name: Frank, bar: 5, drink: wine 

But when I select id 1 and bar 9 I want to get Frank with no drinks.

id: 1, name: Frank

I tried with left join union right join, but I always end up getting unwanted drinks in other bars. I am trying to do this query with MySQL.

This is a left join query with careful filtering:

select t1.*, t2.bar, t2.drink
from t1 left join 
     t2
     on t1.id = t2.id and t2.bar = 9
where t1.name = 'Frank';

The left join ensures that all rows in the first table are in the output. The where then filters these rows to get the name that you want. Key to this is the on clause with the condition on the second table. If there is a match, you will get the matching rows in the second table. Otherwise, you will get a row with NULL values in the t2 columns.

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