MySQL pulls out random data
- 2020-05-06 11:48:42
- OfStack
They all wanted to use PHP's implementation of randomization, but it seems to take more than two queries to get them out.
After going through the manual, I found the following statement. Now I can complete the task, but it is less efficient
SELECT * FROM table_name ORDER BY rand() LIMIT 5;
rand says this in the manual:
RAND()
RAND(N)
Returns a random floating point value in the range 0 to 1.0. If an integer parameter N is specified, it is used as the seed value.
mysql
>
select RAND();
-
>
0.5925
mysql
>
select RAND(20);
-
>
0.1811
mysql
>
select RAND(20);
-
>
0.1811
mysql
>
select RAND();
-
>
0.2079
mysql
>
select RAND();
-
>
0.7888
You cannot use columns with RAND() values in an ORDER BY clause, because ORDER BY will double count columns many times. However, in MySQL 3.23, you can do: SELECT * FROM table_name ORDER BY RAND(), This is in favor of getting one from SELECT * FROM table1,table2 WHERE a=b AND c<
Random sample of the set d ORDER BY RAND() LIMIT 1000. Note that an RAND() in an WHERE clause is reevaluated each time WHERE is executed.
But I tried. For a table of eight thousand records, one execution would take 0.08 sec. A little slower
Later, I consulted google and got the following code
SELECT *
FROM table_name AS r1 JOIN
(SELECT ROUND(RAND() *
(SELECT MAX(id)
FROM table_name)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 5;
Unfortunately, only mysql 4.1.* above supports such a subquery.
Here's what others have added:
select id zhyx_items order by rand() rand
After the sql statement is optimized:
SELECT t1.id
FROM zhyx_items AS t1 JOIN
(SELECT ROUND(RAND() *
((SELECT MAX(id) FROM zhyx_items)-(SELECT MIN(id) FROM zhyx_items))+
(SELECT MIN(id) FROM zhyx_items)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 0,5;