mysql order by rand 优化,如何优化缓慢的MySQL查询由于ORDER BY RAND()?

So I have this relatively simple query to pull a random row based on a few criteria from two different MyISAM tables:

SELECT

table1 . * , table2 . *

FROM

Table1 AS table1

LEFT JOIN

Table2 AS table2

USING (

col1

)

WHERE

table1.col1 != '5324372'

AND

table1.col2 LIKE 'S'

AND (

table1.col3 LIKE 'I'

OR table1.col3 LIKE 'V-G'

)

AND (

table2.col1 = 'A'

OR table2.col2 = 'B'

)

ORDER BY RAND( )

LIMIT 1

...which at the beginning worked fine, but as my Database began to grow, now takes several seconds to execute.

All columns used above are indexed, so it's not an indexing problem.

From what I've researched, it's due to the ORDER BY RAND() line which apparently runs very slow on large tables.

I've seen some potential solutions to this problem, but they are quite cryptic and I could not wrap my head around any of them in relation to my query above.

I'm actually surprised that MySQL does not have a built-in solution to this very slow ORDER BY RAND() problem as it would seem to me like it is a very basic need for many types of applications needing to select a random row.

So how can I optimize my query above so that I get the same/similar effect without the long execution times?

解决方案

You are choosing only one row , I think you can choose one row randomly by LIMIT randomly. Example:

If you have:

SELECT * table ORDER BY RAND( ) LIMIT 1;

change it to

SELECT * table LIMIT $randomvalue ,$randomvalue + 1;

$randomvalue is a random value chosen from the application level.

update: the following answer is more clear than the above one.

//get the total number of rows

$result= mysql_query(" SELECT COUNT(*) AS total FROM `table` ");

$row = mysql_fetch_array($result);

$total=$row['total'];

//create random value from 1 to the total of rows

$randomvalue =rand(1,$total);

//get the random row

$result= mysql_query(" SELECT * FROM `table` limit $randomvalue,1");

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值