Rewrite self join to JPQL

2019-07-09 23:52发布

问题:

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)