Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top