MySQL How to get random data from the table
I have discussed this issue in the group before, and it is quite interesting. The syntax of mysql is really interesting.
They originally wanted to use PHP to achieve randomness, but they took out multiple It seems that more than two queries are required.
I flipped through the manual and found the following statement, which can complete the task
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(); Use RAND for clauses () values use columns because ORDER BY will recalculate the column multiple times. However, in MySQL3.23, you can do: SELECT * FROM table_name ORDER BY RAND(), which is helpful to get a result from SELECT * FROM table1,table2 WHERE a=b AND c
But I tried it. For a table with 8,000 records, it takes 0.08 sec to execute once, which is a bit slow.
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;
Execution efficiency requires 0.02 sec. Unfortunately, only mysql 4.1.* or above supports such a subquery .
http://www.bkjia.com/PHPjc/318428.html