Can anyone explain what is happening with the following SQL? I understand order by rand is not a good practice, but I am interested in an explanation of why this is happening
create database test_views_rand;
use test_views_rand;
create table test_table (number int);
insert into test_table values (1), (2), (3), (4);
select @test := number from test_table order by rand() limit 1;
# selects a random number from 1 - 4
select @test;
# Always gives 4, regardless of what the actual number was in the select query
Just in case it isn’t clear, the first select statement is random as expected. The second select statement always gives 4, regardless of the outcome of the first select statement.
The assignments are done before order by like @bw_üezi said.
results
and then
select @test,@aa,@a,@rresultsHow
@aacan ever be 4 if in the end it is only 2?This is because of the bugfix: http://bugs.mysql.com/bug.php?id=16861
User-variable assignments that are not part of the expression in the select part are done twice (at least for last row, not sure about others)
Manipulating user-variables inside query can often yield in unexpected results.
You are better off using query:
or