I have a doubt on how variables work in mysql. As I read in their web looks like setting a variable will become visible to the next row.
My table is like:
A B C N
1 NULL NULL 4
1 NULL NULL 4
1 1 NULL 4
1 1 NULL 4
1 1 1 4
1 1 1 4
What I want is to return only the rows with C = 1. If no rows then return B = 1 and C is NULL if no rows A = 1 and B is NULL and C is NULL.
My idea was:
select N as number,
@var_c := case when (C = 1) then 1 else -1 end as myc,
@var_b := case when (@var_c < 0 and B = 1) then 1 else -1 end as myB,
@var_c := case when (@var_a < 0 and var_b < 0 and C = 1) then 1 else -1 end as myC
from (select @var_a := -1) r_a,
(select @var_b := -1) r_b,
(select @var_c := -1) r_c,
(select A, B, C, N from my_table order by A desc, B desc, C desc) rows
It should (I want to) return
number myA myB myC
4 -1 -1 1
4 -1 -1 1
4 -1 -1 -1
4 -1 -1 -1
4 -1 -1 -1
4 -1 -1 -1
With this and having myA > 0 or myB > 0 or myC > 0 would work.
But it is returning
number myA myB myC
4 1 -1 -1
4 1 -1 -1
4 -1 -1 1
4 -1 -1 1
4 -1 1 -1
4 -1 1 -1
Shouldn’t Mysql keep the vars across the rows?
Regards.
First of all, do not use variables like this. You shouldn’t expect that you can set a variable in a
FROMclause and then access the value in theSELECTclause. That’s not how variables work. Normally you should only use a variable in one place in the query, otherwise you can get undeterministic results.Second of all, why don’t you just issue three different queries? First for
A = 1 and B is NULL and C is NULL, and if it doesn’t return any rows, issue a query with the second condition set. And so forth.And if you ultimately want to issue just a single query, you can try this:
But it’s very likely to kill performance. So better just use three queries instead of one.
UPD: There’s another (yet similar) approach: