选择记录更改值时

时间:2014-03-27 16:31:37

标签: mysql select triggers

我正在尝试选择与之前的记录相比更改了值的记录,

我的桌子看起来像这样

Id(int) | value(boolean) |
-------------------------
1       | 0              |
-------------------------
2       | 1              |
-------------------------
3       | 1              |
-------------------------
4       | 1              |
-------------------------
5       | 0              |
-------------------------
6       | 0              |
-------------------------

我必须得到身份证明:2,5

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

我做了一次自我加入,但是加入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。

答案 1 :(得分:0)

您可以在查询中使用mysql变量来检查其是新的还是未更改的

SELECT
`Id`, 
`value`,
(CASE when @test=value then 'unchanged'
else 'changed' end) occurance,
@test:=`value`  testvar
FROM
  Table1 
,(SELECT @test:='new') t
HAVING occurance='changed'
ORDER BY `Id`

See fiddle demo