我有一个包含超过 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);
PS:作为一个大且不断增长的表,需要快速查询
最佳答案
显然。不一定有任何行满足 where
条件。
一种替代方法是完全放弃 where
子句:
select t.*
from table t
where `type` = 5
order by rand()
limit 4;
这是一种提高效率的方法(table(type)
上的索引会有所帮助):
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”是任意的。但它通常应该至少获取四行。
关于php - LIMIT 并不总是返回相同的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38626121/