2009-07-17 83 views
0

我有一个类Order包含一组OrderIction本身包含一组OrderItem's。加入HQL子查询

在SQL中,一个可以在JOIN子句中使用SELECT语句,如下面的查询完成:

SELECT 
    o.id, 
    o.amount, 
    sum(s.quantity*s.price), 
    sum(s.quantity*i.price) 
FROM 
    orders AS o 
    JOIN ordersections AS s ON s.order_id=o.id 
    JOIN (SELECT section_id, sum(quantity*price) AS price FROM orderitems GROUP BY section_id) AS i ON i.section_id=s.id 
GROUP BY o.id, o.amount 

有没有可能来表达HQL这样的查询?

回答

2

除非我失去了一些东西,你的查询可以在SQL重写为:

SELECT 
    o.id, 
    o.amount, 
    sum(s.quantity*s.price), 
    sum(s.quantity*i.quantity*i.price) 
FROM orders AS o 
    JOIN ordersections AS s ON s.order_id=o.id 
    JOIN orderitems AS i ON i.section_id=s.id 
GROUP BY o.id, o.amount 

在这种情况下,然后可以在HQL改写为:如果我丢失

SELECT 
    o.id, 
    o.amount, 
    sum(s.quantity*s.price), 
    sum(s.quantity*i.quantity*i.price) 
FROM orders AS o 
    JOIN o.sections AS s 
    JOIN s.items AS i 
GROUP BY o.id, o.amount 

有些东西和上面的查询没有返回你想要的,你用HQL转换运气不好,因为Subqueries in HQL can only occur in SELECT or WHERE clauses。但是,您可以将您的查询映射为<sql-query> - 最终应该没有任何区别。

+0

这并没有给出相同的结果,因为第三列不依赖于该项目,并且将会重复与每个部分中的项目一样多的次数。 除以数字(*)应该做的伎俩,所以感谢您的帮助。 – 2009-07-18 07:55:50