使用 MySQL 选择随机行

Selecting random rows with MySQL(使用 MySQL 选择随机行)
本文介绍了使用 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 选择随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Can#39;t Create Entity Data Model - using MySql and EF6(无法创建实体数据模型 - 使用 MySql 和 EF6)
MySQL select with CONCAT condition(MySQL选择与CONCAT条件)
Capitalize first letter of each word, in existing table(将现有表格中每个单词的首字母大写)
How to retrieve SQL result column value using column name in Python?(如何在 Python 中使用列名检索 SQL 结果列值?)
Update row with data from another row in the same table(使用同一表中另一行的数据更新行)
Exporting results of a Mysql query to excel?(将 Mysql 查询的结果导出到 excel?)