先做个自连接,连接条件为id1=id2+1,让id1正好为id2的下一个自增。 mysql> SELECT a.id id1, b.id id2, a.value value1, b.value value22 -> FROM test a JOIN test b ON a.id = b.id + 1; +------+------+--------+---------+ | id1 | id2 | value1 | value2 | +------+------+--------+---------+ | 2 | 1 | 5 | 2 | | 3 | 2 | 6 | 5 | | 4 | 3 | 10 | 6 | +------+------+--------+---------+ 3 rows in set (0.00 sec)
因为id1为id2的下一个自增,故value1-value2相减为最后的结果。
将上述的自连接结果集写作临时表,让value1与value2相减得到最后的结果: mysql> SELECT value1 - value2 RESULT -> FROM ( -> SELECT a.value value1, b.value value2 -> FROM test a JOIN test b ON a.id = b.id + 1 -> ) t; +--------+ | RESULT | +--------+ | 3 | | 1 | | 4 | +--------+ 3 rows in set (0.00 sec)