php - LIMIT 并不总是返回相同的行数

标签 php mysql yii

我有一个包含超过 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/

相关文章:

PHP 在 session 变量中显示一行 Mysql 结果的每一列 - 刷新下一行

php mysql准备语句绑定(bind)参数错误

php - 使用 ajax 和 jquery 从数据库动态添加预填充表单

MySQL - 插入数据并从表中选择

mysql - yii2 中的多个 where 条件

php - wpdb::prepare() 的查询参数必须有一个占位符

javascript - JSON 编码为 Javascript

php - 如何在mysql标签中显示用户数据?代码

yii - 如何在 yii 中将所有 url 转发到单个 url

php - Yii CJuiDatePicker - 页面上的第二个实例在第一个实例之后未直接打开