I have a table named Work_Items like this:
Assume there are lots of Names (i.e., E,F,G,H,I etc.,) and their respective Date and Produced Items in this table. It’s a massive table, so I’d want to write an optimised query.
In this, I want to query the latest A,B,C,D records.
I was using the following query:
SELECT * FROM Work_Items WHERE Name IN ('A','B','C','D') ORDER BY Date DESC OFFSET 0 LIMIT 4
But the problem with this query is, since I’m ordering by Date, the latest 4 records I’m getting are:
I want to get this result:
Please help me in modifying the query. Thanks.
2
Answers
On MySQL 8+, we can use
ROW_NUMBER
:You can use inner join as follows, its working on any mysql version: