MySQL randomly extracts a certain number of records

MySQL randomly extracts a certain number of records

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

Recommend

CSS element hiding principle and display:none and visibility:hidden

1. CSS element hiding <br />In CSS, there ar...

Pros and Cons of Vite and Vue CLI

There is a new build tool in the Vue ecosystem ca...

A brief discussion on the corresponding versions of node node-sass sass-loader

Table of contents The node version does not corre...

Ubuntu opens port 22

Scenario You need to use the xshell tool to conne...

Object.entries usage you don't know in JavaScript

Table of contents Preface 1. Use for...of to iter...

Detailed tutorial on installing Protobuf 3 on Ubuntu

When to install If you use the protoc command and...

An article to understand the advanced features of K8S

Table of contents K8S Advanced Features Advanced ...

Example analysis to fix problems in historical Linux images

Fix for issues with historical Linux images The E...

Element Table table component multi-field (multi-column) sorting method

Table of contents need: Problems encountered: sol...

How to configure SSL for koa2 service

I. Introduction 1: SSL Certificate My domain name...

js handles account logout when closing the browser

Table of contents Classic approach question Furth...

Best Practices Guide for Storing Dates in MySQL

Table of contents Preface Do not use strings to s...