限制的预测.Disjunction

时间:2011-07-21 04:20:02

标签: nhibernate

使用Restrictions.Discjunction()或Restrictions.Or()的投影将生成WHERE子句而不是HAVING子句。这将导致错误(WHERE子句不能引用聚合表达式)。

示例:

.CreateCriteria(typeof(SalesOrderLine), "SOL")
.CreateCriteria("DeliveryOrderLines", "DOL", JoinType.LeftOuterJoin)
.SetProjection(
    Projections.GroupProperty("SOL.Key").As("SalesOrderLineId"),
    Projections.GroupProperty("SOL.Item"),
    Projections.GroupProperty("SOL.Description"),
    Projections.GroupProperty("SOL.UnitPrice"),
    Projections.GroupProperty("SOL.Quantity"),
    Projections.GroupProperty("SOL.DiscountPercentage"),
    Projections.GroupProperty("SOL.SalesOrder"))
.Add(Restrictions.Or(
    Restrictions.IsNull(Projections.Sum("DOL.Quantity")),
    Restrictions.GtProperty("SOL.Quantity", Projections.Sum("DOL.Quantity")))), 
.List();

SQL结果:

SELECT this_.SalesOrderLineId as y0_, this_.Item as y1_, this_.Description as y2_, this_.UnitPrice as y3_, this_.Quantity as y4_, this_.DiscountPercentage as y5_, this_.SalesOrderId as y6_ FROM SalesOrderLine this_ left outer join DeliveryOrderLine dol1_ on this_.SalesOrderLineId=dol1_.SalesOrderLineId 
WHERE (sum(dol1_.Quantity) is null or this_.Quantity > sum(dol1_.Quantity))
GROUP BY this_.SalesOrderLineId, this_.Item, this_.Description, this_.UnitPrice, this_.Quantity, this_.DiscountPercentage, this_.SalesOrderId

我做错了吗?或者这是Nhibernate 3.1中的错误?

提前致谢:)。

1 个答案:

答案 0 :(得分:1)

上次我检查了Criteria API不支持HAVING子句。你需要使用HQL,它支持HAVING。

要与Criteria API一起使用,您必须将查询修改为:

SELECT this_.SalesOrderLineId as y0_, this_.Item as y1_, this_.Description as y2_, this_.UnitPrice as y3_, this_.Quantity as y4_, this_.DiscountPercentage as y5_, this_.SalesOrderId as y6_ FROM SalesOrderLine this_ left outer join DeliveryOrderLine dol1_ on this_.SalesOrderLineId=dol1_.SalesOrderLineId 
WHERE (select sum(Quantity) from DeliveryOrderLine) is null or (select sum(Quantity) from > SalesOrderLine ) > (select sum(Quantity) from DeliveryOrderLine)
GROUP BY this_.SalesOrderLineId, this_.Item, this_.Description, this_.UnitPrice, this_.Quantity, this_.DiscountPercentage, this_.SalesOrderId

由于多次求和计算,我给出的解决方案会有一些性能损失,但它会完成工作。

你也可以试试这个,但我不确定它是否会正常运行:

SELECT this_.SalesOrderLineId as y0_, this_.Item as y1_, this_.Description as y2_, this_.UnitPrice as y3_, this_.Quantity as y4_, this_.DiscountPercentage as y5_, this_.SalesOrderId as y6_, SUM(dol1_Quantity) as sum1, SUM(this_.Quantity) as sum2 from SalesOrderLine this_ left outer join DeliveryOrderLine dol1_ on this_.SalesOrderLineId=dol1_.SalesOrderLineId 
WHERE sum1 is null or sum1 > sum2
GROUP BY this_.SalesOrderLineId, this_.Item, this_.Description, this_.UnitPrice, this_.Quantity, this_.DiscountPercentage, this_.SalesOrderId

希望这有帮助!