如何在左边连接中获取一行,其中两个右表行在MySQL中匹配两个单独的值?

时间:2017-03-05 15:27:02

标签: mysql sql

我想通过匹配Right Table值与1 AND 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

2 个答案:

答案 0 :(得分:0)

您希望匹配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`

答案 1 :(得分:0)

自连接table2并在第一个中选择值= 1,在第二个中选择值= 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