在作排序时,发现update中的orderby 不起作用,业务功能:按照syl字段进行降序排名:
在mysql5.6版本中运行的sql如下:
UPDATE (SELECT @a := @a + 1 AS rn, id, syl
FROM t_user_syl h, (SELECT @a := 0
) t where h.day=${day}
ORDER BY syl desc
) t1, t_user_syl t2
SET t2.syl_pm = t1.rn
WHERE t2.id = t1.id
在生产发布时,发现排序不正确(mysql5.7)!经分析,应该是order by 执行的顺序问题,改写sql如下:
UPDATE (SELECT @a := @a + 1 AS rn, id, syl
FROM (
select * from t_user_syl
where day=${day}
ORDER BY syl desc
) h, (SELECT @a := 0 ) t
) t1, t_user_syl t2
SET t2.syl_pm = t1.rn
WHERE t2.id = t1.id;
就是把orderby放到最里面,先排好序,然后再生成排名rn!
这就是5.7作了重要改进后遇到的问题,我们在写这类sql时最好还是按改进的sql方法来写!