简体   繁体   中英

How to get a row with left join with two right table row matching two separate value in MySQL?

I want to get Ronald from Left Table through matching Right Table values with 1 AND 2. I know I need to use DISTINCT to get only one row but other than that, I'm stumped.

Left Table

pid | name
1     Ronald
2     Chris
3     John

Right Table

pid | value
1     1
1     2
2     1
3     2

Joined Table

pid | name   | value
1     Ronald   1
1     Ronald   2
2     Chris    1
3     John     2

Expected Output

pid | name
1     Ronald

You want to match both 1 and 2. Aggregation and having come to mind:

select t1.pid, t1.name
from table1 t1 join
     table2 t2
     on t1.pid = t2.pid
where t2.value in (1, 2)
group by t1.pid, t1.name
having count(*) = 2;  -- should be `count(distinct)` if duplicates are possible in `table2`

Self join table2 and select value = 1 in the first and value = 2 in the second. Join the result with table 1.

select t1.pid, t1.name
from table1 t1
join table2 t2_1 on t1.pid = t2_1.pid 
join table2 t2_2 on t2_1.pid = t2_2.pid AND t2_1.value = 1 AND t2_2.value = 2

Or if you like that better:

select t1.pid, t1.name
from table1 t1
join table2 t2_1 on t1.pid = t2_1.pid AND t2_1.value = 1
join table2 t2_2 on t2_1.pid = t2_2.pid AND t2_2.value = 2

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