MTK
MTK

Reputation: 3570

mysql select random from results

I have one table test like that:

real_id    name   active
1           A       0
2           B       1
3           C       1
4           D       1
5           E       0
6           F       1

What I looking for is:

Select rows having active column = 1 and finally get only one random from them

I have tried that:

/*get the max count from recordset*/
SET @rows_count = (SELECT COUNT(*) FROM test WHERE active = 1);
set @fakeId = 0;

SELECT * FROM test, (
    SELECT *, @fakeId := @fakeId + 1 AS fake_id,  
    (ROUND((RAND() * (@rows_count-1))+1)) AS random_nr
    FROM test
    WHERE active = 1
) AS total
WHERE total.fake_id = total.random_nr;
LIMIT 1;

At first sight it seem working good, but if I have tried them several , I have no results from time to time

SOLVED

I have solved them by calculate the random_nr outside of select into a variable

SET @random_nr = (ROUND((RAND() * (@rows_count-1))+1));

And in WHERE clause

WHERE total.fake_id = @random_nr;

Upvotes: 0

Views: 32

Answers (1)

juergen d
juergen d

Reputation: 204746

select * from test where active = 1 order by rand() limit 1

Upvotes: 1

Related Questions