简体   繁体   中英

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):

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 . I you want all pairs that are only related to one 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:

select c1, c2
from t
group by c1, c2
having min(r) = max(r) and min(r) = 'r1'

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