Reputation: 468
Struggling with an SQL query to select the 5 most recent, unique, entries in a MySQL 5.7.22 table. For example, here's the 'activity' table:
uaid nid created
9222 29722 2018-05-17 03:19:33
9221 31412 2018-05-17 03:19:19
9220 31160 2018-05-16 23:47:34
9219 31160 2018-05-16 23:47:30
9218 31020 2018-05-16 22:35:59
9217 31020 2018-05-16 22:35:54
9216 28942 2018-05-16 22:35:20
...
The desired query should return the 5 most recent, unique entries by the 'nid' attribute, in this order (but only need the nid attribute):
uaid nid created
9222 29722 2018-05-17 03:19:33
9221 31412 2018-05-17 03:19:19
9220 31160 2018-05-16 23:47:34
9218 31020 2018-05-16 22:35:59
9216 28942 2018-05-16 22:35:20
I have tried a variety of combinations of DISTINCT but none work, ie:
select distinct nid from activity order by created desc limit 5
What is the proper query to return the 5 most recent, uniq entries by nid?
Upvotes: 1
Views: 64
Reputation: 521987
Your problem is the simplest form of the top-N-per-group problem. In general, this problem is a real headache to handle in MySQL, which doesn't support analytic functions (at least not in most versions folks are using in production these days). However, since you only want the first record per group, we can do a join to subquery which finds the max created
value for each nid
group.
SELECT a1.*
FROM activity a1
INNER JOIN
(
SELECT nid, MAX(created) AS max_created
FROM activity
GROUP BY nid
) a2
ON a1.nid = a2.nid AND a1.created = a2.max_created;
Upvotes: 4
Reputation: 133380
You can use a subquery and join
select * from activity m
inner join (
select nid, min(created) min_date
from activity
group by nid
limit 5
) t on t.nid = m.nin and t.min_date = m.created
Upvotes: 2