mysql快速随机,MySql中的快速随机行

I need to generate a random row from my MySql database and i have found example here:

http://akinas.com/pages/en/blog/mysql_random_row/

And i want to use solution 3 which looks like this:

$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");

$offset_row = mysql_fetch_object( $offset_result );

$offset = $offset_row->offset;

$result = mysql_query( " SELECT * FROM `users` LIMIT $offset, 1 " );

My code looks like this now:

$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users` ");

$offset_row = mysql_fetch_object( $offset_result );

$offset = $offset_row->offset;

$result = mysql_query( "SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1 " );

$random_date = mysql_fetch_array($result);

echo $random_date['user_name']; //display username of random user

But when i refresh the page: approximatly 7 of 10 times nonthing shows up. No username at all and also im trying to print out the id of the user but it's also empty.

It seems that it's not getting anything at all from the database when refreshing and sometimes it get's data from the database. Any idea why this might happen?

解决方案

In this particular case, the problem is that you're working with two different queries; the first query is:

SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `users`

Whereas the second one includes a condition:

SELECT * FROM `users` WHERE profile_image='2' LIMIT $offset, 1

^^^^^^^^^^^^^^^^^^^^^^^

Both queries should operate over the same result set.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值