使用 MySQL 选择随机行 [英] Selecting random rows with MySQL

查看:48
本文介绍了使用 MySQL 选择随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多关于这个主题的话题,但我一直没有成功理解如何去做.

例如,如果我有这张表:

+------+-------+-------+|身份证 |姓名 |类 |+------+-------+-------+|5 |测试 |一 ||10 |测试2 |一 ||12 |测试5 |一 ||7 |测试6 |二 |+------+-------+-------+

我只想显示一"类中的 X 个随机行,我该怎么做?

注意:这是一张大桌子,所以我不想使用ORDER BY RAND.

解决方案

正如您所知,大多数人推荐的 ORDER BY RAND() 解决方案不能扩展到大型表.

>

SET @r := (SELECT FLOOR(RAND() * (SELECT COUNT(*) FROM mytable)));SET @sql := CONCAT('SELECT * FROM mytable LIMIT 1 OFFSET', @r);从@sql 准备 stmt1;执行 stmt1;

我在我的书中介绍了这个和其他解决方案,SQL 反模式:避免陷阱数据库编程.

<小时>

如果你想用 PHP 做到这一点,你可以这样做(未测试):

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();

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.

解决方案

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();

这篇关于使用 MySQL 选择随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆