我有一个表测试,其中包含以下属性: id ,水果。
我们在上表中有以下内容:
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'
此查询仅返回其中一个苹果。
感谢您的帮助! 托比。
答案 0 :(得分:2)
实际上,最有效的方法是使用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)
上的索引。
答案 1 :(得分:1)
您必须加入桌面才能获得所需的结果:
{{1}}
答案 2 :(得分:1)
您可以使用子查询查找重复项,以及获取行的外部查询;
SELECT * FROM testing
WHERE fruits IN (
SELECT fruits FROM testing
GROUP BY fruits HAVING COUNT(*)>1
)
ORDER BY id