从以下四个记录中,我想选择OwnerId
第二个最新记录
ItemId OwnerId Date
11477 20981 2013-05-13
11477 1 2013-05-21
11477 21086 2013-05-22 #this is the one I'm talking about
11477 3868 2013-05-24
怎么办?
这需要ItemID
指定,
SELECT *
FROM TableName
WHERE ItemID = '11477'
ORDER BY DATE DESC
LIMIT 1,1
但是,如果您不想指定ItemID
,并且想要获取 every 的所有第二条最新记录,则可以使用相关子查询根据 lastest为 eachItemID
生成序列号,ItemID
DATE
SELECT ItemId, OwnerID, Date
FROM
(
SELECT A.ItemId,
A.OwnerId,
A.Date,
(
SELECT COUNT(*)
FROM tableName c
WHERE c.ItemId = a.ItemId AND
c.Date >= a.Date) AS RowNumber
FROM TableName a
) x
WHERE RowNumber = 2
select ownerid
from your_table
order by date desc
limit 1, 1
我认为您可以按ORDER BY
日期降序排列,这将为您提供从新到旧的顺序,然后 LIMIT 1,1
仅获得第二个结果,这应该是您要查找的结果
SELECT *
FROM table
ORDER BY date DESC
LIMIT 1,1