SQL运行报错:Incorrect usage of UNION and ORDER BY 问题
执行如下图 sql语句时报错 :Incorrect usage of UNION and ORDER BY
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc
union all
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc
union all
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc
是因为UNION 和order by 一起使用时,如果没有括号的情况下,只能使用一个order by。所以加上括号就可以了:
select * from(
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc)a
union all
select * from(
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc)b
union all
select * from(
select st1.*,c.c_name ,sc1.s_score from table1 t1 left join table2 t2 on t2.t_id = t1.t_id order by t2.id desc)c
问题解决。