小编典典

将自联接重写为JPQL

sql

我需要将此自我联接转换为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

编辑:解决方法:

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

我在lastUpdateDate上使用了一个额外的select语句,而不是自我连接。

编辑2: 这是一个更好的解决方案,因为它还包含NULL值。唯一的缺点是我不能使用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)

阅读 181

收藏
2021-05-23

共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)
2021-05-23