例如这样的语句:
select * from table1 where name like '%name1%' order by ID ASC
union
select * from table2 where name like '%name2%' order by ID DESC
提交到MySQL中会报错:
MySQL:Incorrect usage of union and order by
如果去掉一个order by:
select * from table1 where name like '%name1%'
union
select * from table2 where name like '%name2%'order by ID DESC
这样就变成了先union,然后再对整个结果集进行排序
如果对每个select加上括号:
(select * from table1 where name like '%name1%' order by ID ASC)
union
(select * from table2 where name like '%name2%' order by ID DESC)
这样不报错了,但是order排序完全没起作用。
正确的方式是建立临时表,然后排序:
select * from
(select * from table1 where name like '%name1%' order by ID ASC) table3
union
select * from
(select * from table2 where name like '%name2%' order by ID DESC) table4
P.S.union与union ALL作用区别在于,union自带去重功能,而union ALL只是简单的合并结果,没有去重。