获取值从0更改为1的行

时间:2015-02-27 09:52:51

标签: mysql sql

我有桌子:

id date default(bool)
1 2015-01-01 0
2 2015-01-02 0
3 2015-01-03 1
4 2015-01-04 1
5 2015-01-05 1
6 2015-01-06 0
7 2015-01-07 0
8 2015-01-08 1
9 2015-01-09 1
10 2015-01-10 0

我只想按日期排序的行将默认列从0更改为1,因此在此表中行:3和8.

2 个答案:

答案 0 :(得分:1)

如果可以使用id而不是date,请使用相关的子查询来读取上一行的值:

select *
from tablename t1
where default = 1
  and (select default from tablename t2
       where t2.id = t1.id - 1) = 0

使用日期代替查找上一行:

select *
from tablename t1
where default = 1
  and (select default from tablename t2
       where t2.date = (select max(date) from tablename
                        where date < t1.date)) = 0

答案 1 :(得分:0)

这是使用动态变量

的另一种方法
select t.id,t.date,t.`default` 
    from ( 
       select 
       t1.*, 
       @default := if(@prev_default = 0 and t1.`default` = 1,1,0) as def,
       @prev_default:=t1.`default` 
       from (
         select * from test order by date
       )t1,
       (select @prev_default:= 2,@default:=0)r
    )t 
    where t.def = 1 ;