[英]Mysql: how to select rows where the combination of 2 of the column values are unique given a certain other column value
我有一个像表(id,C1,C2,R,..)
表,在此表中, C1-C2
对与一个或多个R
,例如(id1,a,b,r1,...)
(id2,a,b,r2,...)
我想找出所有仅与某个R
相关的C1-C2
对(例如对于r1
,则不包括ab
对,因为它也与r2
),我应该如何编写查询?
You could group by C1 and C2 and count the number of "r"s that are equal to the value you want (and make sure it's not 0) and the number of "r"s that aren't (and make sure it is 0): 您可以将C1和C2分组,然后计算等于您想要的值的“ r”的数量(并确保其不为0)和不等于的“ r”的数量(并确保其为0):
SELECT c1, c2
FROM mytbale
GROUP BY c1, c2
HAVING COUNT(CASE r WHEN 'r1' THEN e END) > 0 AND
COUNT(CASE r WHEN 'r1' THEN NULL ELSE 1 END) = 0
If I understand correctly, you can use group by
and having
. 如果我理解正确的话,你可以用
group by
和having
。 I you want all pairs that are only related to one r
: 我想要所有只与一个
r
相关的对:
select c1, c2, max(r) as r
from t
group by c1, c2
having min(r) = max(r);
If you have a particular r
in mind: 如果你有一个特别的
r
记:
select c1, c2
from t
group by c1, c2
having min(r) = max(r) and min(r) = 'r1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.