Mysql LEFT JOIN ON倒数第二个id

时间:2014-10-02 13:17:19

标签: mysql left-join

我有这个问题试图总结时间:

SELECT t1.id, t1.number, t1.time - COALESCE(SUM(t2.time), 0) time FROM times t1 
LEFT JOIN times t2 ON t1.number = t2.number AND t2.id < t1.id
GROUP BY t1.id, t1.number, t1.time

输出:

id          number          time (in seconds)
--------------------------------------------
1            9              65
2            5              78
3            7              92

它工作正常,但我只需要在子句(t2.id < t1.id)中与LEFT JOIN条件的倒数第二个相加。

1 个答案:

答案 0 :(得分:1)

用于选择倒数第二个id

SELECT t1.id, t1.number, t1.time - COALESCE(SUM(t2.time), 0) time FROM times t1 
LEFT JOIN times t2 ON t1.number = t2.number 
AND t2.id = (select id from times order by id desc limit 1,1)
GROUP BY t1.id, t1.number, t1.time