sql - MySQL assign user-defined variable in where clause -
the 1st query sql converted to:
select name,(@num) test 1
in select clause, (@num : @num + 1)
return 1, mean last query sql equal to:
select name,(@num) test 1 <= 1
?
if yes, why 2nd query return first record?
if no, (@num := @num + 1)
in where
clause?
why @num
in 3rd query 4
?
create table test ( id int(1), name varchar(10) ); insert test (id, name) values (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'); set @num := 0; select name, @num test (@num := 1) <= 1; -- return records. set @num := 0; select name, @num test (@num := @num + 1) <= 1; -- return first record. set @num := 0; select name, @num test (@num := @num + 1) <= 1 order name; -- return 1 record, name = a, @num = 4
case 1st query:
the first query resolves following equivalent query:
set @num := 0; select name, @num test (@num := 1) <= 1; v set @num := 0; select name, @num test 1 <= 1; v set @num := 0; select name, @num test true;
so, records. in every iteration 1
assigned @num
. so, @num
doesn't change.
case 2nd query:
in case of second query in first iteration resolves above query.
1st iteration:
select name, @num test (@num := @num + 1) <= 1; v @num 1 select name, @num test 1 <= 1;
2nd iteration:
@num 2 select name, @num test 2 <= 1;
3rd iteration:
@num 3 select name, @num test 3 <= 1; ........ .... , on
look here first iteration qualifies condition in clause. others dropped.
Comments
Post a Comment