HQL Select where Row appears more than once

冷暖自知 提交于 2019-12-23 04:43:57

问题


I am attempting to bring back rows where two column values appear more than once. Note, this is not a priority. For example, in the table..

ID    Name    Country
1     Dave    UK
2     Jim     UK
3     Dave    UK
4     Dave    US
5     Jim     US

Then it would return row 1 and row 3, but none of the others. This is because the combination of "Dave" and "UK" only appears in those rows. I am struggling to implement a HQL query to obtain this. To get things going, I tried to group on just name:

from Runner r group by r.name having count(r.name) > 1

But I received the following exception:

Column "RUNNER0_.ID" must be in the GROUP BY list;

I read on why this is logically necessary, so now I'm stuck as to how I'm meant to implement this functionality.

I am using Grails 2.4.4, JDK 7, Hibernate 4.3.6.1


回答1:


You can try searching duplicates using exists with sub-query.

select r 
from Runner r 
where exists
(
    select rn
    from Runner rn
    where rn.id <> r.id 
    and rn.name = r.name
    and rn.country = r.country
)



回答2:


One approach is to use subqueries:

from Runner r
where (r.name, r.country) in 
   (select name, country from Runner group by name, country having count(*) > 1)


来源:https://stackoverflow.com/questions/32220835/hql-select-where-row-appears-more-than-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!