everyone。使用多個連接將MYSQL查詢轉換爲HQL
我使用Grails與MySQL 3.3.0.M2框架作爲數據源下面的SQL查詢工作正常
SELECT
c.name,
SUM(CASE
WHEN t.status = 'open' THEN 1
ELSE 0
END) 'open',
SUM(CASE
WHEN t.status = 'pending' THEN 1
ELSE 0
END) 'in progress',
SUM(CASE
WHEN t.status = 'closed' THEN 1
ELSE 0
END) 'closed'
FROM
tickets t
INNER JOIN
users u ON t.user_id = u.id
INNER JOIN
user_coordinations uc ON uc.user_id = u.id
INNER JOIN
coordinations c ON c.id = uc.coordination_id
GROUP BY 1
我使用隱式連接翻譯成HQL,但我得到錯誤的結果,這裏是HQL查詢:
SELECT
c.name,
SUM(CASE
WHEN t.status = 'open' THEN 1
ELSE 0
END),
SUM(CASE
WHEN t.status = 'pending' THEN 1
ELSE 0
END),
SUM(CASE
WHEN t.status = 'closed' THEN 1
ELSE 0
END)
FROM
Ticket t, User u, UserCoordination uc, Coordination c
WHERE
MONTH(t.dateCreated) = :month
GROUP BY 1
爲了得到正確的結果堆棧溢出用戶幫助我明白,查詢需要使用顯式連接,這裏的問題是:Group by a field that does not belongs to the consulted table
現在我用下面的查詢嘗試:
SELECT
c.name,
SUM(CASE
WHEN t.status = 'open' THEN 1
ELSE 0
END),
SUM(CASE
WHEN t.status = 'pending' THEN 1
ELSE 0
END),
SUM(CASE
WHEN t.status = 'closed' THEN 1
ELSE 0
END)
FROM
Ticket t
INNER JOIN
User u
INNER JOIN
UserCoordination uc
INNER JOIN
Coordination c
WHERE
MONTH(t.dateCreated) = :month
GROUP BY 1
但我得到一個com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException與消息引起您有一個錯誤的SQL語法;檢查對應於你的MySQL服務器版本的手冊正確的語法使用近「內部聯接user_coordinations usercoordi2_的內連接配位coordinat」在行1
感謝您的幫助和時間
感謝您回答@vahid。 '選擇新... ...對我來說是新的。我可以看到構建查詢的優點。關於這個問題,我得到一個_org.hibernate.QueryException_引起的消息:_could不能解析屬性:userCoordination:ni.edu.ucc.leon.User_ – user615274
我認爲這是因爲有一個一對多的用戶和協調。我如何在查詢中表達這一點?在這個位置有一個SQL小提琴:http://sqlfiddle.com/#!9/9ed08/1 – user615274
@yuor第一個問題,你有'UserCoordination'我不知道你的域對象映射是什麼。所以如果'User hasMany = [ucord:UserCoordination]'那將是'left join u.ucord uc'這是你在域對象中聲明的映射。關於你的第二個問題,一對多是通過「左連接」來滿足的,在這裏某些東西是空的或者某些東西有一些價值,這將捕獲所有東西。如果你從'join'中省略'left'字,那麼它會列出1條記錄。所以當左連接和user1有兩條記錄時,它會出現兩次 – Vahid