Rewrite self join to JPQL

假如想象 提交于 2019-12-11 02:55:50

问题


I need to convert this self join to JPQL:

SELECT s1.*
FROM site AS s1
JOIN (SELECT site_type, MAX(last_update_date) AS LastUpdate
      FROM site
      WHERE site.last_update_date > "2011-02-27 16:57:53"
      GROUP BY site_type) AS s2
ON s1.site_type = s2.site_type
AND s1.last_update_date = s2.LastUpdate
ORDER BY s1.last_update_date DESC

Edit: the solution:

SELECT s1
FROM Site s1 
WHERE s1.lastUpdateDate = ( SELECT MAX(s2.lastUpdateDate) 
                            FROM Site s2 
                            WHERE s1.siteType = s2.siteType)
AND s1.lastUpdateDate > "2011-02-27 16:57:53"
ORDER BY s1.lastUpdateDate DESC

Instead of a self-join I used an extra select statement on lastUpdateDate.

Edit 2: this is a better solution since it also includes NULL values. The only downside is that I cannot use a TypedQuery.

SELECT s.id, s.url, s.siteType, MAX(s.lastUpdateDate) as maxLastUpdateDate 
FROM Site s 
GROUP BY s.siteType 
HAVING (maxLastUpdateDate < "2011-02-27 16:57:53" OR maxLastUpdateDate IS NULL)

回答1:


SELECT s.id, s.url, s.siteType, MAX(s.lastUpdateDate) as maxLastUpdateDate 
FROM Site s 
GROUP BY s.siteType 
HAVING (maxLastUpdateDate < "2011-02-27 16:57:53" OR maxLastUpdateDate IS NULL)


来源:https://stackoverflow.com/questions/9533068/rewrite-self-join-to-jpql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!