我有一个超过800K行的表.我想要随机获得4个ID.我的查询工作得很快,但它有时给我一个,有时两个,有时没有给出结果.知道为什么吗?
这是查询:
select * from table
where (ID % 1000) = floor(rand() * 1000)
AND `type`='5'
order by rand()
limit 4
type =’5’只有1603行,并不总是给我4行.当我将其更改为type = ’11’时,它可以正常工作.知道如何解决这个问题吗?
这是我在Yii的代码
$criteria = new CDbCriteria();
$criteria->addCondition('`t`.`id` % 1000 = floor(rand() * 1000)');
$criteria->compare('`t`.`type`', $this->type);
$criteria->order = 'rand()';
$criteria->limit = 4;
return ABC::model()->findAll($criteria);
解决方法:
明显.没有任何行符合where条件.
另一种方法是完全免除where子句:
select t.*
from table t
where `type` = 5
order by rand()
limit 4;
这是一种提高效率的方法(并且表上的索引(类型)有帮助):
select t.*
from table t cross join
(select count(*) as cnt from table t where type = 5) x
where `type` = 5 and
rand() <= 5*4 / cnt
order by rand()
limit 4;
“5”是任意的.但它通常应该至少获取四行.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。