主页

TP查询数据去重并按指定字段排序

拭朱砂   IP属地: 青海
0 点赞 0阅读 952

使用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();

© 著作权归作者所有,转载或内容合作请联系作者