简体   繁体   English

MySQL:如何在给定其他某个列值的情况下选择其中两个列值的组合唯一的行

[英]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 byhaving 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.

相关问题 MySQL-仅选择列具有唯一值的行 - Mysql - Select only rows where column has unique value 在MySQL中,如何为给定列仅选择具有特定值的行? - In MySQL, how do I select only rows with certain values for a given column? Select 行与其他两列的每个唯一组合的 Max(列值) - Select rows with Max(Column Value) for each unique combination of two other columns MYSQL从column2 = value的列中选择唯一值并计算找到每个唯一值的次数 - MYSQL SELECT unique values from column where column2 = value & count how many times each unique value was found 如何选择行以组合列值 - how to select rows for combination of column values 表的SELECT计数,其中列为CONNECT,但与其他相关列相关的其他行没有特定值 - SELECT count from table where column is CONNECT but other rows with related other column does not have a certain value MySQL - 如何删除列不包含某些值的行? - MySQL - How to delete rows where column does not contain certain values? MySQL选择列值唯一的地方 - MySql Select Where Column Value Is Unique MySQL SELECT唯一列,其他列为max - MySQL SELECT unique column where other column is max 选择在指定列中具有最高值的行,而在其他列中不具有唯一值的行应该是不同的 - Select rows with highest value in a specified column and not unique values in other column should be distinct
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM