3

我已经被这个查询困住了一段时间了。SQL 返回我想要的结果,但我不知道如何用 HQL 表达查询。

这是SQL

select      thread.ThreadId,
            thread.Title,
            thread.CreatedOn, 
            thread.ViewCount,
            thread.CreatedBy,
            thread.ForumId 

from Threads thread 
where 
    (thread.ThreadId in(select post.ThreadId from Posts post 
    where (post.CreatedBy=2 )))

AND

(2!=(select TOP 1 post2.CreatedBy from Posts post2 
        where (post2.ThreadId=thread.ThreadId ) ORDER BY post2.CreatedOn DESC))

我想我需要使用 DetachedCriteria 来创建相关的子查询,但我遇到了真正的问题。

这是到目前为止的位置:

DetachedCriteria latestPostInThread = DetachedCriteria.For(typeof (ForumPost), 
                    "post2")
            .Add(Expression.EqProperty("post2.ThreadId", "post.ThreadId"))
            .AddOrder(Order.Desc("CreatedOn"))
            .SetFirstResult(0)
            .SetMaxResults(1);

对于主要查询

ICriteria critMain = CreateCriteria(typeof (ForumPost), "post")
            .Add(Expression.Eq("CreatedBy",user.ID))
            .Add(Subqueries.Ne("CreatedBy", latestPostInThread));

这显然是不正确的 - 我需要从 latestPostInThread 获取 userId 才能将其用作我的子查询,但我完全被难住了。

任何帮助将不胜感激!我不愿意回退到 SQL,因为我确信在 nHibernate 中实现并不是特别困难。

4

0 回答 0