1

从以下四个记录中,我想选择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

怎么办?

4

3 回答 3

2

这需要ItemID指定,

SELECT *
FROM   TableName
WHERE  ItemID = '11477'
ORDER  BY DATE DESC
LIMIT  1,1

但是,如果您不想指定ItemID,并且想要获取 every 的所有第二条最新记录,则可以使用相关子查询根据 lastest为 eachItemID生成序列号,ItemIDDATE

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
于 2013-06-02T14:53:01.730 回答
0
select ownerid
from your_table
order by date desc
limit 1, 1
于 2013-06-02T14:53:22.513 回答
0

我认为您可以按ORDER BY日期降序排列,这将为您提供从新到旧的顺序,然后 LIMIT 1,1仅获得第二个结果,这应该是您要查找的结果

SELECT *
FROM table
ORDER BY date DESC
LIMIT 1,1
于 2013-06-02T14:53:35.267 回答