如何在where子句中设置用户变量(mysql 5.7)

时间:2019-02-03 13:37:48

标签: mysql user-variables

我创建了一个桌子座位,例如:

seat   status
1   y
2   y
3   n
4   n
5   n
6   y
7   n
8   n
9   n
10  n
11  n
12  y
13  y
14  n
15  n

并且我想基于mysql5.7为客户找到三个连续的席位

并且我尝试使用user_variable来使嵌套循环无效:

select seat - 2 begin, seat end
from (
       select seats.seat, case when status = 'y' then @a := 0 else @a := @a + 1 end as a
       from seats,
            (select @a := 0) s) t
where a >= 3;

效果很好。 但是我只想对表进行一次全扫描。所以我尝试将变量推到这样的位置:

select seats.*, @a, @s, @e
from seats , (select @a := 0, @s := -1, @e := -1) s
 where
       case when status = 'n' then @a := @a + 1
           when status = 'y' then @a := 1
         else null  end; -- and
       -- having @a=1
#        case when @a > 3 then @s := seat else  @s:= -1 end and
#        case when @a > 3 then @e :
#
#        = seat - 2 else  @s:= -1 end ;

但是:结果集显示

seat   status   @a     @s       @e
1   y   1   -1  -1
2   y   1   -1  -1
3   n   2   -1  -1
4   n   3   -1  -1
5   n   4   -1  -1
6   y   4   -1  -1
7   n   5   -1  -1
8   n   6   -1  -1

乍一看似乎只能正常工作,那么如何多次在where子句中设置use-variable?

0 个答案:

没有答案