HQL / SQL根据计数选择前10个记录

时间:2012-06-19 17:51:10

标签: mysql sql hibernate hql

我有两张桌子:

CATEGORY (id)
POSTING (id, categoryId)

我正在尝试编写HQL或SQL查询来查找排名最多的前10个类别。

非常感谢帮助。

4 个答案:

答案 0 :(得分:5)

SQL查询:

SELECT  c.Id, sub.POSTINGCOUNT
FROM CATEGORY c where c.Id IN
( 
    SELECT TOP 10 p.categoryId
    FROM POSTING p
    GROUP BY p.categoryId 
    order by count(1) desc
)

HQL:

Session.CreateQuery("select c.Id
        FROM CATEGORY c where c.Id IN
        ( 
            SELECT  p.categoryId
            FROM POSTING p
            GROUP BY p.categoryId 
            order by count(1) desc
        )").SetMaxResults(10).List();

http://sqlinthewild.co.za/index.php/2010/01/12/in-vs-inner-join/

答案 1 :(得分:1)

在SQL中你可以这样做:

SELECT c.Id, sub.POSTINGCOUNT
FROM CATEGORY c 
INNER JOIN 
( 
    SELECT p.categoryId, COUNT(id) AS 'POSTINGCOUNT'
    FROM POSTING p
    GROUP BY p.categoryId
) sub ON c.Id = sub.categoryId
ORDER BY POSTINGCOUNT DESC
LIMIT 10

答案 2 :(得分:0)

SQL可以是:

SELECT c.* from CATEGORY c, (SELECT count(id) as postings_count,categoryId
FROM POSTING 
GROUP BY categoryId ORDER BY postings_count
LIMIT 10) d where c.id=d.categoryId

此输出可以映射到类别实体。

答案 3 :(得分:0)

我知道这是一个老问题,但我得到了满意的答案。

JPQL:

//the join clause is necessary, because you cannot use p.category in group by clause directly
@NamedQuery(name="Category.topN", 
     query="select c, count(p.id) as uses 
            from Posting p 
            join p.category c 
            group by c order by uses desc ")

爪哇:

List<Object[]> list = getEntityManager().createNamedQuery("Category.topN", Object[].class)
            .setMaxResults(10)
            .getResultList();
//here we must made a conversion, because the JPA cannot order using a non select field (used stream API, but you can do it in old way)
List<Category> cats = list.stream().map(oa -> (Category) oa[0]).collect(Collectors.toList());