我有以下需要转换为nhibernate的查询:
SELECT o.*
FROM orders o
INNER JOIN
(
-- get the most recent orders based on end_date (this implies the same order can exist in the orders table more than once)
SELECT o2.order_id, MAX(o2.end_date) AS max_end_date
FROM orders o2
GROUP BY o2.order_id
) most_recent_orders
ON o.order_id=most_recent_orders.order_id
AND o.end_date=most_recent_orders.max_end_date
-- of the most recent orders, get the ones that are complete
WHERE o.is_complete=1
我知道hql不支持加入子查询,这就是为什么这不起作用。我不能使用“in”语句,因为子查询正在选择2个值。我尝试使用hibernate文档中的建议:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-tuple
from Cat as cat
where not ( cat.name, cat.color ) in (
select cat.name, cat.color from DomesticCat cat
)
但是这引发了一个错误,因为Sql Server不喜欢“in”语句中的多个值。
任何帮助将不胜感激!我对使用Criteria或Hql的解决方案持开放态度。
答案 0 :(得分:0)
这是使用子查询来实现相同的
var maxDateQuery = DetachedCriteria.For<Order>()
.Add(Restrictions.PropertyEq("OrderId", "order.OrderId"))
.SetProjection(Projections.Property("EndDate"));
var results = session.CreateCriteria<Order>("order")
.Add(Subqueries.Eq("EndDate",maxDateQuery))
.Add(Restrictions.Eq("IsComplete", true))
.List<Order>();