mysql查询怎么随机获取数据? [ 2.0 版本 ]
用Yii框架模型怎么写随机获取数据?不是用sql语句,求帮忙,
/*
* 随机获取10道题
*/
public function getRandquestions(){
return $this->find()->offset(0)->limit(10)->asArray()->all();
}
共 3 个回答
-
1) 采用官方的方式
select * from tb_name order by rand() limit N
2)采用类似偏移方式
select * from tb_name where id >= (select floor(max(id) * rand()) from tb_name ) order by id asc limit N;
3)优化的方式
select * from tb_name as r1 join (select round(rand() * (select max(id) from tb_name)) as id2) as r2 where r1.id >= r2.id2 order by r1.id asc limit N;
共 2 条回复zone_g@163.com 回复于 2019-04-28 21:22 回复@lzrqyc110
`$query = HappyBank::find();$query->alias('r1'); $query->join('JOIN', "(SELECT ROUND(RAND() * (". HappyBank::find()->select('MAX(id)')->createCommand()->getRawSql() .")) AS id2) AS r2"); $query->where("r1.id >= r2.id2"); $query->orderBy([ 'r1.id' => SORT_ASC ]);
// var_dump($query->createCommand()->getRawSql());
var_dump($query->all());` 不知道你还用不用得上
lzrqyc110
注册时间:2016-01-02
最后登录:2018-12-28
在线时长:29小时34分
最后登录:2018-12-28
在线时长:29小时34分
- 粉丝37
- 金钱4195
- 威望40
- 积分4885