In mysql, the random data reading method may be the simplest and most commonly used function rand (). However, if there is a problem with tens of millions of data, I will introduce it below.
In mysql, the random data reading method may be the simplest and most commonly used function rand (). However, if there is a problem with tens of millions of data, I will introduce it below.
Simplest approach
Rand () function instance
| The code is as follows: |
|
|
SELECT * FROM table_name order by rand () LIMIT 5; |
Time spent: 0.7888
In this case, when the data volume is large, you can find a solution.
| The code is as follows: |
|
|
SELECT * FROM table_name AS r1 JOIN (select round (RAND () * (select max (id) FROM table_name) AS id)
R2 WHERE r1.id> = r2.id order by r1.id asc limit 5; |
Time spent 0.02 sec
The preceding statement uses JOIN, which is used on the mysql Forum.
| The code is as follows: |
|
|
SELECT *
FROM 'table'
WHERE id> = (select floor (MAX (id) * RAND () FROM 'table ')
Order by id LIMIT 1; |
I tested it. it took 0.5 seconds and the speed was good, but there was still a big gap with the above statements. I always feel that something is abnormal.
So I changed the statement.
| The code is as follows: |
|
|
SELECT * FROM 'table'
WHERE id> = (SELECT floor (RAND () * (select max (id) FROM 'table ')))
Order by id LIMIT 1; |
The query efficiency is improved, and the query time is only 0.01 seconds.
Finally, complete the statement and add the MIN (id) judgment. In the initial test, I did not add the MIN (id) judgment.
The first few rows in the table are always queried in half of the time.
The complete query statement is:
| The code is as follows: |
|
|
SELECT * FROM 'table'
WHERE id> = (SELECT floor (RAND () * (select max (id) FROM 'table')-(select min (id) FROM 'table') +
(Select min (id) FROM 'table') order by id LIMIT 1;
SELECT *
FROM 'table' AS t1 JOIN (select round (RAND () * (select max (id) FROM 'table')-(select min (id) FROM
'Table') + (select min (id) FROM 'table') AS id) AS t2
WHERE t1.id> = t2.id
Order by t1.id LIMIT 1; |
Finally, these two statements are queried 10 times in php respectively,
The former takes 0.147433 seconds.
The latter takes 0.015130 seconds.