![](/img/trans.png)
[英]query for join two column and get one row per left with column that have array of right table refrenced to left table row
[英]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.