Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php LIMIT并不总是返回相同数量的行_Php_Mysql_Yii - Fatal编程技术网

Php LIMIT并不总是返回相同数量的行

Php LIMIT并不总是返回相同数量的行,php,mysql,yii,Php,Mysql,Yii,我有一张超过800K行的桌子。我想随机得到4个身份证。我的查询速度很快,但它有时会给我一个,有时会给我两个,有时甚至没有给出结果。知道为什么吗 以下是查询: select * from table where (ID % 1000) = floor(rand() * 1000) AND `type`='5' order by rand() limit 4 type='5'只有1603行,并不总是给我4行。当我将其更改为type='11'时,它工作正常。你知道怎么解决这个问题吗

我有一张超过800K行的桌子。我想随机得到4个身份证。我的查询速度很快,但它有时会给我一个,有时会给我两个,有时甚至没有给出结果。知道为什么吗

以下是查询:

select * from table
  where (ID % 1000) = floor(rand() * 1000)
  AND `type`='5'
  order by rand()
  limit 4
type='5'只有1603行,并不总是给我4行。当我将其更改为type='11'时,它工作正常。你知道怎么解决这个问题吗

这是我的代码

$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;
以下是一种提高效率的方法,表类型索引有助于:


第5条是任意的。但是它通常应该至少获取四行。

对每一行重复使用rand函数,因此可以得到匹配的泊松分布数。可能是0,可能是1,可能是312-概率不同。

如果您需要快速查询,那么不要在MySQLRelated中使用rand:您可以记录rand的泊松分布性质吗。我很确定这是一个统一的分布,两者是非常不同的。
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;