Selecting random rows with MySQL

2019-01-02 21:13发布

I saw many topics about this subject and I have been unsuccessful in understanding how to do it.

For example, if I have this table:

+------+-------+-------+
| id   | name  | class |
+------+-------+-------+
|    5 | test  | one   | 
|   10 | test2 | one   | 
|   12 | test5 | one   | 
|    7 | test6 | two   | 
+------+-------+-------+

and I want to show only X random rows from class "one", how can I do that?

NOTE: it's a big table, so I don't want to use ORDER BY RAND.

标签: mysql random
3条回答
情到深处是孤独
2楼-- · 2019-01-02 21:38

The ORDER BY RAND() solution that most people recommend doesn't scale to large tables, as you already know.

SET @r := (SELECT FLOOR(RAND() * (SELECT COUNT(*) FROM mytable)));
SET @sql := CONCAT('SELECT * FROM mytable LIMIT 1 OFFSET ', @r);
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

I cover this and other solutions in my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming.


If you want to do this with PHP, you could do something like this (not tested):

<?php
$mysqli->begin_transaction();
$result = $mysqli->query("SELECT COUNT(*) FROM mytable")
$row = $result->fetch_row(); 
$count = $row[0]; 
$offset = mt_rand(0, $count);
$result = $mysqli->query("SELECT * FROM mytable LIMIT 1 OFFSET $offset");
...
$mysqli->commit();
查看更多
若你有天会懂
3楼-- · 2019-01-02 21:49
SELECT * FROM `table` WHERE `class`="one" ORDER BY RAND() LIMIT 5
查看更多
永恒的永恒
4楼-- · 2019-01-02 21:53
select ID, NAME, CLASS
from YOURTABLE
where CLASS='one'
order by rand()
limit $x

ordering by rand() is not particularly efficient, but it's about the smallest/quickest way of doing it.

查看更多
登录 后发表回答