从以下四条记录中,我想选择第二条最新记录的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
如何去做?
答案 0 :(得分:2)
这需要指定ItemID
,
SELECT *
FROM TableName
WHERE ItemID = '11477'
ORDER BY DATE DESC
LIMIT 1,1
但是,如果您不想指定ItemID
,并且希望获得每个ItemID
的所有第二个最新记录,则可以使用相关子查询为每个创建序列号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
答案 1 :(得分:0)
select ownerid
from your_table
order by date desc
limit 1, 1
答案 2 :(得分:0)
我认为您可以ORDER BY
日期降序,这将为您提供从较新到较旧的订单,然后LIMIT 1,1
仅获取第二个结果,该结果应该是您要查找的结果< / p>
SELECT *
FROM table
ORDER BY date DESC
LIMIT 1,1