使用group('data_id')分组和distinct去重并按id排序并不生效,去重是去重了,但排序没有生效
model('AnswerLog')->order('id DESC')->distinct(true)->group('data_id')->field('id,data_id')->where(['type'=>2,'is_end'=>'1'])->select()
有效方法
重要:一定要加field字段过滤字段,否则数据会错乱
// 子查询:找出每个title的最新createtime
$subQuery = Db::name('AnswerLog')
->field('id,data_id, MAX(createtime) as maxtime')
->group('data_id')
->where(['user_id'=>$this->auth->id,'type'=>2,'is_end'=>'1'])
->buildSql();
// 主查询:根据子查询的结果获取最新的数据
$result = Db::name('AnswerLog')
->alias('a')
->field('a.id,a.data_id, a.createtime,a.title,a.fraction,a.pass_mark')
->join([$subQuery => 'b'], 'a.data_id = b.data_id AND a.createtime = b.maxtime')
->order('a.createtime', 'desc') // 重新排序,确保最新的记录排在最前面
->where(['a.user_id'=>$this->auth->id,'a.type'=>2,'a.is_end'=>'1'])
->select();