从mysql数据库中提取5条随机记录 [英] Pull 5 random records from mysql database

查看:871
本文介绍了从mysql数据库中提取5条随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个php/mysql脚本,该脚本将从数据库中提取5条随机记录并显示它们.目前,我正在使用以下内容提取一条记录并将其显示在模块中,但是我不确定如何一次只提取5条记录.我在数据库中总共大约有200-300条记录.

I am trying to write a php / mysql script that will pull 5 random records from the DB and display them. At the moment I am using the following to pull one record out and display it in a module, but im not sure how to pull out 5 at a time only. I will have approx 200-300 records in the DB in total.

我目前正在使用以下代码随机提取单个记录:

I am currently using the following code to pull the single record out at random :

<?php
$result = mysql_query("SELECT * FROM `zgjzb_chronoforms_data_submitbusiness` ORDER BY     RAND() LIMIT 0,4;");
$row = mysql_fetch_array($result);
?>

推荐答案

您不想使用ORDER BY RAND(). MySQL必须建立一个临时表.如果您的表具有唯一的id列,则如下所示会更好:

You don't want to use ORDER BY RAND(). MySQL has to build a temporary table. If your table has a unique id column, something like this is much better:

SELECT * FROM `zgjzb_chronoforms_data_submitbusiness` 
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` )
ORDER BY id LIMIT 1;

请参见此博客文章,以了解在php中效果很好的其他方法.

See this blog post for other approaches that work well in php.

这篇关于从mysql数据库中提取5条随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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