我试图只选择与以前的记录相比改变了值的记录,
我的 table 是这样的
Id(int) | value(boolean) |
-------------------------
1 | 0 |
-------------------------
2 | 1 |
-------------------------
3 | 1 |
-------------------------
4 | 1 |
-------------------------
5 | 0 |
-------------------------
6 | 0 |
-------------------------
我必须得到 id:2,5
谢谢你的帮助
最佳答案
我做了一个自连接,但不是连接相同的 id
,而是连接 t1.id = t2.id-1
然后比较值:
select t2.id
from thetable t1
inner join thetable t2 on t1.id = t2.id-1
where t1.value != t2.value
sqlfiddle:http://sqlfiddle.com/#!2/6d626/4
编辑添加: 感谢@Ravinder,我想出了一种方法来做到这一点,即使 id 不是连续的。 我用了this related question .
SET @a :=0;
SET @b :=1;
SELECT t1.id, t1.rownum
FROM
(SELECT if(@a, @a:=@a+1, @a:=1) as rownum, id, value FROM thetable) AS t1
LEFT JOIN
(SELECT if(@b, @b:=@b+1, @b:=1) as rownum, id, value FROM thetable) AS t2
ON t1.rownum = t2.rownum
where t2.value != t1.value
SQLFiddle with non-sequential ids
基本上,如果您没有顺序 ID,您可以创建自己的 ID。我称它们为 rownum。
关于mysql - 记录更改值时选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22693689/