第一种写法:
SELECT * FROM t_kaoqin
WHERE p_id=1 AND TO_DAYS(t_kaoqin.kq_time)=TO_DAYS(NOW())
GROUP BY user_id
ORDER BY kq_time DESC
问题:发现先执行的group by,后执行order by,我要的结果是先排序再分组。
第二种写法:
SELECT temp.* FROM(
SELECT * FROM t_kaoqin
WHERE p_id=1 AND TO_DAYS(t_kaoqin.kq_time)=TO_DAYS(NOW())
ORDER BY kq_time DESC
) AS temp GROUP BY temp.user_id
问题:本以为将排序写成一个子查询应该会先排序后分组,执行后发现问题同第一种写法一样。
第三种写法(最终解决的写法):
SELECT temp.* FROM(
SELECT * FROM t_kaoqin
WHERE p_id=1 AND TO_DAYS(t_kaoqin.kq_time)=TO_DAYS(NOW())
ORDER BY kq_time DESC LIMIT 0,10000
) AS temp GROUP BY temp.user_id
解决方式:在子查询中添加LIMIT 0,10000则可使子查询语句即排序执行完再进行分组。