mysql> set @last_id := -1;Query OK, 0 rows affected (0.00 sec)mysql> select id, A, B, result -> from -> ( -> select -> table1.*, -> @last_id, -> if(@last_id < 0, null, id - @last_id) as result, -> @last_id :...
求MYSQL数据库中上下相邻两行的差
这个结果要从第一个开始吗?那样就有点复杂了。这个行不行,结果是从第二行开始的:
mysql> set @last_id := -1;Query OK, 0 rows affected (0.00 sec)mysql> select id, A, B, result -> from -> ( -> select -> table1.*, -> @last_id, -> if(@last_id < 0, null, id - @last_id) as result, -> @last_id := id -> from -> table1 -> ) as tmp -> ;+----+------+------+--------+| id | A | B | result |+----+------+------+--------+| 1 | 2 | 1 | NULL || 21 | 1 | 1 | 20 || 33 | 3 | 2 | 12 |+----+------+------+--------+3 rows in set (0.00 sec)2013-12-09
SELECT t1.id,t1.a,t1.b,t2.id-t1.id as resultFROM (select a.id,a.a,a.b,count(*) as rownum from table1 a,table1 b where a.id>=b.id group by a.id,a.a,a.b) t1LEFT JOIN (select a.id,a.a,a.b,count(*) as rownum from table1 a,table1 b where a.id>=b.id group by a.id,a.a,a.b) t2 ON t1.rownum=t2.rownum-1有问题再追问吧
这是假定你的id都是依次递增的,,,因为我看你没有自增字段的
2013-12-09