2009-07-17 106 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