有SQL:
select COUNT(1) from
(SELECT TOP 10 Status
FROM SESSIONS
where SERVER_ID = 2569
ORDER by ID desc) as s
where s.STATUS = 32768
如何在NHiberbate中创建Criteria?语言C#.
var subQuery = DetachedCriteria.For(typeof(Session))
.SetProjection(Property.ForName("Status"))
.Add(Restrictions.Eq("Server", server))
.AddOrder(Order.Desc("Id"))
.SetMaxResults(10);
var query = DetachedCriteria.For(typeof(Session))
.Add(Subqueries.Exists(subQuery))
.Add(Restrictions.Eq("Status.Id", valueFailStatus))
.SetProjection(Projections.RowCount());
using (var session = NHibernateHelper.OpenSession())
return (int)query.GetExecutableCriteria(session)
.UniqueResult();
但是我得到了整个表的样本,而不是这10个元素中的一个.
最佳答案 现在,只要此子查询返回任何结果,您的查询就会告诉我使用StatusId为valueFailStatus的会话.
由于您使用的是Exists,因此您不会将查询关联在一起以执行您想要的操作.
我认为你正在寻找Subqueries.PropertyIn.像这样的东西:
var subQuery = DetachedCriteria.For(typeof(Session))
.SetProjection(Property.ForName("Id"))
.Add(Restrictions.Eq("Server", server))
.AddOrder(Order.Desc("Id"))
.SetMaxResults(10);
var query = DetachedCriteria.For(typeof(Session))
.Add(Subqueries.PropertyIn("Id", subQuery))
.Add(Restrictions.Eq("Status", 32768))
.SetProjection(Projections.RowCount());
var result = (int)query.GetExecutableCriteria(s)
.UniqueResult();
…将生成如下所示的SQL:
SELECT
count(*) as y0_
FROM
Sessions this_
WHERE
this_.Id in (
SELECT
TOP (10) this_0_.Id as y0_
FROM
Sessions this_0_
WHERE
this_0_.Server_Id = 2569
ORDER BY
this_0_.Id desc
)
and this_.Status = 32768