Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(your code is missing an <code>INSERT</code> keyword) On my version of MySQL (5.5), these are my results</p> <pre><code>drop table if exists test_table; create table test_table (number int); insert into test_table (number) 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; </code></pre> <p>Results</p> <pre><code>3,4,3,1,4,3,4,3,1,3 </code></pre> <p>However, if you order by rand(now()) and do it quickly, it will stick at 4....3....2....4... because it is no longer <code>random</code>, you have given it a specific seed.</p> <p>If you run it with <strong>order by rand(1), the answer is ALWAYS the same</strong>, because you have asked it to seed based on 1 consistently.</p> <p><hr> To see what RAND() produces (which is what is used to sort the rows), check out this query:</p> <pre><code>select rand() from ( select 1 union all select 2 union all select 1 union all select 2 union all select 2 ) x; </code></pre> <p>Run it many times. Then swap for rand(now()) and run it many times quickly. Then swap for rand(1) and run again.</p> <p><hr> To see how this actually affects your query, just remove the ORDER BY and see the magic happening.</p> <pre><code>select @test := number, rand(2) from test_table order by rand(2) </code></pre> <p>Change rand(2) to rand(1) or just rand() <em>(remember to change in both places)</em>. Watch the 2 columns closely. As for how <code>@test :=</code> works, it <em>does</em> set it to the first row. BUT, it continues to set it for <em>EVERY</em> row, and ends up with the value set at the last row encountered.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload