mysql随机查询5条数据库,从mysql数据库中提取5条随机记录

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 :

$result = mysql_query("SELECT * FROM `zgjzb_chronoforms_data_submitbusiness` ORDER BY RAND() LIMIT 0,4;");

$row = mysql_fetch_array($result);

?>

解决方案

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;

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值