Code to retrieve random data from MySQL database table_PHP tutorial

WBOY
Release: 2016-07-21 15:54:45
Original
1017 people have browsed it

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

truehttp: //www.bkjia.com/PHPjc/318428.htmlTechArticleHow does MySQL take out random data from the table? This issue has been discussed in the group before. It is quite interesting. The syntax of mysql It’s really fun. They originally wanted to use PHP to implement randomization, but taking out multiple items seems to require...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!