Mysql 获取每个产品的前两项记录

Mysql 获取每个产品的前两项记录,mysql,greatest-n-per-group,Mysql,Greatest N Per Group,我有一个包含三个字段的表,如下所示,每个产品都有多个记录。我想知道如何才能为每种产品获得前2名?我已经按时间字段对记录进行了排序 eventId productId time 1 10568 2011-08-30 15:06:57 2 10568 2011-08-30 15:06:56 3 10568 2011-08-30 15:06:53 4 10568 2011-08-30 15:06:50

我有一个包含三个字段的表,如下所示,每个产品都有多个记录。我想知道如何才能为每种产品获得前2名?我已经按时间字段对记录进行了排序

eventId productId time 1 10568 2011-08-30 15:06:57 2 10568 2011-08-30 15:06:56 3 10568 2011-08-30 15:06:53 4 10568 2011-08-30 15:06:50 5 10111 2011-08-30 15:06:56 6 10111 2011-08-30 15:06:53 7 10111 2011-08-30 15:06:50 8 10000 2011-08-30 15:06:56 9 10000 2011-08-30 15:06:53 10 10000 2011-08-30 15:06:50 eventId productId时间 1 10568 2011-08-30 15:06:57 2 10568 2011-08-30 15:06:56 3 10568 2011-08-30 15:06:53 4 10568 2011-08-30 15:06:50 5 10111 2011-08-30 15:06:56 6 10111 2011-08-30 15:06:53 7 10111 2011-08-30 15:06:50 8 10000 2011-08-30 15:06:56 9 10000 2011-08-30 15:06:53 10 10000 2011-08-30 15:06:50
有没有专家能帮助我获得每种产品的前2项记录?

我手头没有SQL编辑器,但它可能看起来像这样:

select * 
from table t 
inner join (select distinct productId as productId from table) table2 
  on (table2.productid = t.productid
where table.time >= (select time from table innertable 
                     where productid = t.productid 
                     order by time desc 
                     limit 1 offset 1) 
SELECT * FROM theTable WHERE eventId IN 
    (SELECT TOP(2) eventId FROM theTable as innerTable 
        WHERE innerTable.productId = theTable.productId)

将“表格”替换为您的表格名称。

按照
best-n-per-group
标记进行操作。这个问题在Stack Overflow上已经被回答了几十次。TOP是针对SQLSERVER的,MYSQL使用LIMITyep,您必须在ROWNUM(我猜Limit 2)获得组中的前2个位置进行操作,没有offsetGood查询,但它将排除只有一个事件的产品。可通过添加或使用相同的子选择来解决,但限制为1,无偏移。我还修正了一个小的打字错误。