MySQL 为两列选择"distinct/unique"条记录



我有这个表:

id  user    value
1   A       Cool
2   A       Cool
3   A       Cool
2   A       Warm
3   A       Warm
4   B       Cool
5   C       Cool
5   C       Warm

我想在这里得到的是一张有"酷"值而没有"暖"值的唱片。这可以通过ID和User列来识别。

我试着做这样的事情:

SELECT DISTINCT id, user FROM log_table where value= 'Cool'

但这仍然会返回同样有"温暖"的记录

预期输出为:

id  user    value
1   A       Cool
4   B       Cool

我发现Distinct的另一个问题是,它不允许我添加*,或者我不知道如何添加,因为当我尝试时,它是一个错误。我也可以在distinct后面加concat吗?没有在不同的功能中处理它?

我可能在这里错误地使用了Distinct。

您可以对预期结果使用条件聚合

select id, user 
from log_table 
group by id, user 
having count(case when value= 'Cool' then 1 else null end) > 0
and  count(case when value= 'Warm' then 1 else null end) = 0

演示

或者你可以使用exists

select id, user 
from log_table a
where a.value = 'Cool'
and not exists (
select 1
from log_table
where a.id = id and a.user = user
and value= 'Warm'
)

演示

考虑以下内容:

SELECT * 
FROM my_table x 
LEFT 
JOIN my_table y 
ON y.id = x.id 
AND y.user = x.user 
AND y.value = 'warm' 
WHERE x.value = 'cool';
+----+------+-------+------+------+-------+
| id | user | value | id   | user | value |
+----+------+-------+------+------+-------+
|  1 | A    | Cool  | NULL | NULL | NULL  |
|  2 | A    | Cool  |    2 | A    | Warm  |
|  3 | A    | Cool  |    3 | A    | Warm  |
|  4 | B    | Cool  | NULL | NULL | NULL  |
|  5 | C    | Cool  |    5 | C    | Warm  |
+----+------+-------+------+------+-------+

我将把剩下的问题留给读者练习。

最新更新