0

如何从user_id=@userid 我的表用户中选择 user_id, SUB(row, row - 1) id 为1、3、4、10、11、23 ...(不是 ++)

--id---------user_id------unixtime--
635918634   1529906793  1374253286
635918635   1529906793  1374253287
635957809   1529906793  1374253583
635957810   1529906793  1374253883
635957811   1529906793  1374254183

我希望

--id-----------user_id--------unixtime-------**SUB(row, row -1)**
635918634   1529906793  1374253286      0
635918635   1529906793  1374253287      1   
635957809   1529906793  1374253583      296     
635957810   1529906793  1374253883      300
635957811   1529906793  1374254183      300

使用SUB(row, row -1) : (unixtime row - unixtime near row before)

4

1 回答 1

0

Using user variables to add a sequence (using 2 different staring sequence numbers), then joining on sequence

SELECT Sub1.id, Sub1.user_id, Sub1.unixtime, Sub1.unixtime - IFNULL(Sub2.unixtime, 0)
FROM
(
    SELECT id, user_id, unixtime, @row = @row + 1 AS RowNum
    FROM SomeTable
    CROSS JOIN (SELECT @row = 1) t
    ORDER BY user_id, unixtime
) Sub1
LEFT OUTER JOIN
(
    SELECT id, user_id, unixtime, @row = @row + 1 AS RowNum
    FROM SomeTable
    CROSS JOIN (SELECT @row = 0) t
    ORDER BY user_id, unixtime
) Sub2
ON Sub1.RowNum = Sub2.RowNum

(not tested)

于 2013-08-01T08:23:26.037 回答