使用 PHP 从 SQL 中选择随机行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8200189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select Random Row from SQL Using PHP
提问by nickw444
I want to request 5 random rows from my SQL table using php. for instance, i need to:
我想使用 php 从我的 SQL 表中请求 5 个随机行。例如,我需要:
mysql_query("SELECT * FROM catalogue >> not sure what goes here << LIMIT 5");
回答by Pheonix
SELECT * FROM catalogue order by RAND() LIMIT 5
Edit:
编辑:
For what its worth, Please note that using rand() on a table with large number of rows is going to be slow. This can actually crash your server.
对于它的价值,请注意在具有大量行的表上使用 rand() 会很慢。这实际上会使您的服务器崩溃。
Some Solution:
一些解决方案:
MediaWiki uses an interesting trick (for Wikipedia's Special:Random feature): the table with the articles has an extra column with a random number (generated when the article is created). To get a random article, generate a random number and get the article with the next larger or smaller (don't recall which) value in the random number column. With an index, this can be very fast. (And MediaWiki is written in PHP and developed for MySQL.)
MediaWiki 使用了一个有趣的技巧(针对 Wikipedia 的 Special:Random 功能):包含文章的表有一个带有随机数的额外列(在创建文章时生成)。要获取随机文章,请生成一个随机数并获取随机数列中下一个更大或更小(不记得是哪个)值的文章。使用索引,这可以非常快。(而 MediaWiki 是用 PHP 编写并为 MySQL 开发的。)
But this is for a single random row only.
但这仅适用于单个随机行。
回答by timonwimmer
Assuming the table has AUTO INCREMENT on you could get the biggest ID with
假设表上有 AUTO INCREMENT 你可以获得最大的 ID
SELECT id FROM catalogue ORDER BY id DESC LIMIT 1
and the smallest ID with
和最小的ID
SELECT id FROM catalogue ORDER BY id ASC LIMIT 1
making it possible to do this
使其有可能做到这一点
$randomId = mt_rand($smallestId, $biggestId);
$randomSql = mysql_query("SELECT * FROM catalogue WHERE id='$randomId'");
For five rows you could create the random ID five times.
对于五行,您可以创建五次随机 ID。
回答by Nonym
If you're selecting random rows from a very large table, you may want to experiment with the approaches in the following link:
如果您从一个非常大的表中选择随机行,您可能需要尝试以下链接中的方法:
http://akinas.com/pages/en/blog/mysql_random_row/
http://akinas.com/pages/en/blog/mysql_random_row/
note: just to share other options with everyone
注意:只是为了与大家分享其他选项