In the past, I used to directly order by rand() to handle this kind of usage scenario, but the efficiency was really not satisfactory. So I encountered this scenario again recently and looked for a better solution online. 1.order by rand() Writing method: SELECT id FROM `table` ORDER BY rand() The disadvantage of this writing method is that the rand function is executed multiple times in the order by, affecting efficiency. 2. max(id) * rand() using join Writing method: 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; The big guys on the Internet all recommend the second way of writing, so I'd like to record it down. I feel that the maximum id and the minimum id can be calculated in the program. The problem here is that if you take multiple records, they must be continuous, so if you don't want to take continuous data, you have to loop. However, this statement is extremely efficient, so loop query can be done. The above are all the relevant knowledge points. Friends in need can learn from them. Thank you for your support of 123WORDPRESS.COM. |
<<: Element sample code to implement dynamic table
>>: How to install babel using npm in vscode
Table of contents 1. Introduction 2. select 2.1 Q...
1. Introduction When we log in to MySQL, we often...
To perform incremental backup of the MySQL databa...
1. What is CSS Animations is a proposed module fo...
Ubuntu's own source is from China, so the dow...
This article shares the specific code for the WeC...
Table of contents 1. Shopping cart example 2. Cod...
Table of contents 1. Application and configuratio...
Starting from this article, a new series of artic...
1. Modify the firewall settings and open the corr...
Generally, we rarely meet HR, but once we do, it c...
XML is designed to describe, store, transmit and ...
background This bug was caused by滾動條占據空間. I check...
I have encountered the problem that MySQL can con...
Special symbols Named Entities Decimal encoding S...