문제

I've got the following query to get the latest row in each group

SELECT s1.* FROM ps s1
JOIN (
   SELECT s2.id FROM ps s2
   WHERE s2.userId = 63
   ORDER BY s2.date DESC
) as a
ON (s1.id = a.id)
GROUP BY s1.name

However this query is performing very poorly. Is there an equivalent query that could get rid of the subqueries and/or any other optimization that could be done?

도움이 되었습니까?

해결책

You can do this using not exists, by choosing rows where there is no larger date for a given name:

select ps.*
from ps
where not exists (select 1
                  from ps ps2
                  where ps2.name = ps.name and
                        ps2.userid = 63 and
                        ps2.date > ps.date
                 ) and
      ps.userid = 63;

This will work best with an index on ps(name, userid, date).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top