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
1. CSS element hiding <br />In CSS, there ar...
There is a new build tool in the Vue ecosystem ca...
This article is a MySQL configuration file soluti...
Table of contents The node version does not corre...
Scenario You need to use the xshell tool to conne...
Download the latest version of MySQL for Ubuntu L...
Table of contents Preface 1. Use for...of to iter...
When to install If you use the protoc command and...
Table of contents K8S Advanced Features Advanced ...
Fix for issues with historical Linux images The E...
Table of contents need: Problems encountered: sol...
I. Introduction 1: SSL Certificate My domain name...
Table of contents Classic approach question Furth...
The main contents of this article are as follows:...
Table of contents Preface Do not use strings to s...