mysql randomly selects a certain number of record examples to explain

  • 2021-12-12 06:09:52
  • OfStack

In the past, this kind of usage scenario was handled directly by order by rand (), but the efficiency is really not flattering, so I recently encountered this kind of scenario again, and found a better solution on the Internet.

1.order by rand()

Writing:


SELECT
  id
FROM
  `table`
ORDER BY
  rand()

The disadvantage of this writing is that the rand function is executed many times in order by, which affects the efficiency.

2. max (id) * rand () uses join

Writing:


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 bosses on the Internet recommend the second writing method. It is hereby recorded that the maximum id and the minimum id can be calculated in the program.

There is a problem here is that if you take more than one, then 1 will be continuous, so if you don't want to take continuous data, you have to cycle, but this statement is extremely efficient, so circular query can be done.

The above is all the relevant knowledge points, friends in need can learn, thank you for your support of this site.


Related articles: