I always thought that MySQL would randomly query several pieces of data.
Select
*
From
'
Table
'
Order
By
Rand
() Limit
5
You can.
However, the test results show that the efficiency is very low. It takes more than 8 seconds to query 5 data records in a database with more than 0.15 million entries
According to the official manual, Rand () is executed multiple times in the order by clause, which is naturally inefficient and inefficient.
You cannot use a column with RAND () values in an order by clause,
Because order by wowould evaluate the column multiple times.
Search for Google. Basically, data is randomly obtained by querying max (ID) * rand () on the Internet.
Select
*
From
'
Table
'
As
T1
Join
(
Select
Round
(
Rand
()
*
(
Select
Max
(ID)
From
'
Table
'))
As
ID)
As
T2
Where
T1.id
> =
T2.id
Order
By
T1.id
ASC
Limit
5
;
However, five consecutive records are generated. The solution is to query only one item at a time and query five times. Even so, it is worthwhile because it takes less than 0.15 million seconds to query 0.01 tables.
The preceding statement uses join, Which is used on the MySQL forum.
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.
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. At the beginning of the test, because I did not add the min (ID) Judgment, half of the results were always queried.
The first few rows in.
The complete query statement is:
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.
It seems that using the join syntax is much more efficient than using functions directly in the WHERE clause.