sql - MySQL RAND() strange behaviour -


I am trying to get a random row from the result of a SQL query.

My query is as

  SET @rank = 0; SELECT * FROM (SELECT (@rank: = @ rank + 1) as raw, WHERE raw.num = FLOOR (1 + (RAND) * @ as AS, ... FROM ... WHERE ....) Rank) Limited 1   

The general idea is that each row in the table is given a unique number (number) from the internal query result. I have manually checked that this is really a matter and every line is being counted.

The last line is causing me trouble as it stands, WHERE num = FLOOR (1 + (RAND (* * @rank)) is returning LIMIT 1 What I need - just half the time it appears to be returning random rows within the correct range (for example, I'm testing the query I is 0-1299). However, one in three questions does not give absolutely anything.

OK, so I thought it was a double precision issue, so I did not have the & gt; = using the following type: where number & gt; = FLOOR (1 + (rand () * @Rank)) LIMIT 1 . The result in this case is confusing me, with this code I always get a result, but the number of returning row is always & lt; 100.

So if we say FLOOR (1 + (rand () * @Rank)) x . When I = to & gt; = , then it confirms that x should be (in some cases) equal to more than 1000 numbers However, when & gt; = , then the condition is that the condition is satisfied, does that mean that the x should always be less than 100?

What's going on? Or how can I solve my problem

I think the problem is that RAND () is calling the function in your query multiple times, once for every row returned from raw , if it is happening, then it is possible that any Rows that will not satisfy undoubtedly, because it is comparing each line with a different goal. (What is the fifth line in the first line? The second row is the third line? Etc.)

I will call the call at the beginning of the RAD @ RAM and at the beginning of the call, something like this:

  SET @rand = RAND (); SET @Rank = 0; Raw WHERE raw.num = FLOOR (1 + @rand * @rank) as SELECT * FROM (SELECT (@Rank: = @ rank + 1) AS num, ... FROM ... WHERE ....) LIMIT 1   

(I prefer pre, because it runs in the same statement, this user is not dependent on the variable, which is being set out of the selection statement .)

But both of them should ensure that the RAND () function is being addressed just once (at the beginning of your query).

Besides, I do not have a good explanation about the behavior you are seeing.

Comments