gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:54:11 27 4
gpt4 key购买 nike

我有这张表:

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

我想要得到的是具有“Cool”值且没有“Warm”值的记录。这可以通过 ID 和用户列来识别。

我试过这样做:

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

但这仍然会返回同样有“Warm”的记录

预期输出是:

id  user    value
1 A Cool
4 B Cool

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

我可能在这里错误地使用了 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

Demo

或者你可以使用 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

关于MySQL 为两列选择 "distinct/unique"条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51284401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com