简体   繁体   English

MySQL为两列选择“不同/唯一”记录

[英]MySQL select “distinct/unique” records for two columns

I have this table: 我有这张桌子:

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

What I want to get here is the record that has the value of "Cool" and that it doesn't have "Warm". 我想得到的是具有“ Cool”值且没有“ Warm”值的记录。 This can be identified by the ID and the User column. 可以通过ID和“用户”列进行标识。

I tried doing something like this: 我试图做这样的事情:

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

But this will still return the record that also has "Warm" 但这仍会返回也有“温暖”的记录

Expected output is: 预期输出为:

id  user    value
1   A       Cool
4   B       Cool

Another problem I found with Distinct is that it doesn't let me add * or I don't how to do it since when I tried it was an error. 我发现Distinct的另一个问题是,它不允许我添加*或者由于我尝试这样做是错误的,所以我不怎么做。 Can I add concat after distinct as well? 我也可以在不同之后添加concat吗? Without it being treated in the distinct function? 没有在独特功能中对其进行处理?

I may be using Distinct wrongly here. 我在这里可能错误地使用了Distinct。

You could use conditional aggregation for your expected results 您可以将条件汇总用于预期结果

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

Demo 演示

Or you could use exists 或者你可以使用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'
)

Demo 演示

Consider the following: 考虑以下:

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  |
+----+------+-------+------+------+-------+

I'll leave the rest of the problem as an exercise for the reader. 我将剩下的问题留给读者练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM