1

抱歉,如果这是一个愚蠢的问题,但我整个下午都在解决这个问题,但找不到解决方案,因为我不熟悉复杂的 SQL:

我想从表中查找“发送消息数量 > 阈值的前 n 个消息发送用户”,这是我的标准:

Criteria c = session.createCriteria(Message.class);
ProjectionList plist = Projections.projectionList();
plist.add(Projections.groupProperty("user"));
plist.add(Projections.rowCount() , "count");
c.setProjection(plist);
c.addOrder(Order.desc("count"));

c.setFirstResult(0);
c.setMaxResults(count);

这是我可以写的,但它缺少“过滤行数低于某个阈值的行”。如何用标准来实施它?非常感谢 !

- - - - - - - 更新 - - - - - - - - - - - -

谢谢@TheStijn,我试过了。我现在可以使用子查询来实现我的目标,但是生成的查询不是那么聪明!查看生成的 SQL:

select
    this_.fromUser as y0_,
    count(*) as y1_ 
from
    Message this_ 
where
    this_.fromUser is not null 
    and this_.created>? 
    and this_.created<? 
    and ? <= (
        select
            count(*) as y0_ 
        from
            Message msg_ 
        where
            msg_.fromUser=this_.fromUser 
            and msg_.fromUser is not null 
            and msg_.created>? 
            and msg_.created<?
    ) 
group by
    this_.fromUser 
order by
    y1_ desc limit ?

也就是说,子查询重复了大部分主查询,我认为这有点多余。是否有任何标准可以构建此类 SQL 查询:

select
    this_.fromUser as y0_,
    count(*) as y1_ 
from
    Message this_ 
where
    this_.fromUser is not null 
    and this_.created>? 
    and this_.created<? 
    and y1_ > ? // threshold
group by
    this_.fromUser 
order by
    y1_ desc limit ?

非常感谢 !

(使用 HQL 来执行此操作似乎要容易得多,但我对 Criteria 方式感到好奇)

4

1 回答 1

2

您将需要一个额外的子查询,例如:

    DetachedCriteria subQuery = DetachedCriteria.forClass(Message.class, "msg");
    subQuery.add(Restrictions.eqProperty("msg.user", "mainQuerymsg.user"));
    subQueryEntriesCount.setProjection(Projections.rowCount());

    c.add(Subqueries.lt(1L, subQuery));

mainQuerymsg <您的主要标准,因此您需要使用别名创建这些标准createCriteria(MEssage.class, "alias")

于 2011-03-24T13:49:14.010 回答