簡體   English   中英

在MySQL中,如何獲得帶有左連接和兩個右表行匹配兩個單獨值的行?

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

我想通過將右表值與1和2匹配來從左表中獲取Ronald。我知道我需要使用DISTINCT來僅獲取一行,但除此之外,我很困惑。

左表

pid | name
1     Ronald
2     Chris
3     John

右表

pid | value
1     1
1     2
2     1
3     2

聯接表

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

預期產量

pid | name
1     Ronald

你想同時匹配1和2的聚合與having浮現在腦海中:

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`

自聯接table2,並在第一個中選擇value = 1,在第二個中選擇value = 2。 將結果與表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

或者,如果您更喜歡:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM