gpt4 book ai didi

mysql - SQL 按属性分组并在该组中有多个时显示结果

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:17 25 4
gpt4 key购买 nike

我有一个表,testing,具有以下属性:idfruits

我们在上述表格中有以下内容:

id, fruits

1, Apple
2, Banana
3, Apple

我想要一个按水果分组的查询(苹果在一组,香蕉在另一组),如果该组中有超过 1 个则返回。

因此,对于上面的示例,查询应返回:

1, Apple
3, Apple

这是我目前所拥有的:

SELECT *
FROM testing
GROUP BY 'fruits'
HAVING COUNT(*) > 1
ORDER BY 'id'

这个查询只返回一个苹果。

感谢您的帮助!托比。

最佳答案

实际上,最有效的方法可能是使用exists:

select t.*
from testing t
where exists (select 1
from testing t2
where t2.fruits = t.fruits and t2.id <> t.id
);

为了获得最佳性能,您需要在 testing(fruits, id) 上建立索引。

关于mysql - SQL 按属性分组并在该组中有多个时显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36240922/

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