Skip to content
Advertisement

MySQL: select row only where closest to date has column value

I want to return all rows that were public in May (2019-05), so if a row was turned to draft (and not back to public) at any point before the end of May, I don’t want it. For example:

The desired result for the above would return post_id 2 because its last status change prior to the end of May was to public.

post_id 1 was put back in draft before the end of May, so it would not be included.

I’m not sure how to use the correct join or sub-queries to do this as efficiently as possible.

Advertisement

Answer

You seem to want the status as of 2019-05-31. A correlated subquery seems like the simplest solution:

To get the ones that are public, just add a WHERE condition:

For performance, you want an index on (post_id, date).

You can also phrase this using a JOIN:

I would expect the correlated subquery to have better performance with the right indexes. However, sometimes MySQL surprises me.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement