mysql5.5根据条件进行排序查询 TP5

用到了 order by if 和 count

使用的是TP5.0

$sql = Db::name('teacher')
            ->alias('t')
            ->join('user u', 'u.user_id  = t.user_id')
            ->join('tiwen tw', 'tw.teacher_user_id = u.user_id', 'left')
            ->field([
                't.*',
                'count(if(tw.is_pingjia = 1, 1, NULL)) nu'
            ])
            ->group('u.user_id')
            ->order('count(if(tw.is_pingjia = 1, 1, null)) desc, count(tw.tiwen_id) desc')
            ->buildSql(true);

打印出语句为

SELECT `t`.*,count(if(tw.is_pingjia = 1, 1, NULL)) nu FROM `yed_teacher` `t` INNER
JOIN `yed_user` `u` ON `u`.`user_id`=`t`.`user_id` LEFT JOIN `yed_tiwen` `tw` ON `tw`.`teacher_user_id`=`u`.`user_id`
GROUP BY `u`.`user_id` ORDER BY count(if(tw.is_pingjia = 1, 1, 0)) desc, count(tw.tiwen_id) desc

上述为查询讲师的回答学员提问评价满意数进行排序,其次根据回答学员提问数进行排序,包含回答数为0的讲师

原文地址:https://www.cnblogs.com/init-007/p/14137751.html