简体   繁体   English

在数据库中选择5个最新的唯一条目

[英]Select 5 most recent unique entries in a database

Struggling with an SQL query to select the 5 most recent, unique, entries in a MySQL 5.7.22 table. 试图通过SQL查询来选择MySQL 5.7.22表中的5个最新的唯一条目。 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): 所需查询应按“ nid”属性按此顺序返回5个最新的唯一条目(但仅需要nid属性):

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: 我已经尝试过DISTINCT的各种组合,但是没有用,即:

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? 通过nid返回5个最新的uniq条目的正确查询是什么?

Your problem is the simplest form of the top-N-per-group problem. 您的问题是每组N个问题中最简单的形式。 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). 总的来说,这个问题在不支持解析功能的MySQL中实在令人头疼。 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. 但是,由于您只希望每个组的第一条记录,我们可以对子查询进行联接,以查找每个nid组的最大created值。

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;

在此处输入图片说明

Demo 演示

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM