在MySQL中,想要对表的多次查询结果分别排序合并是不可行的
如:
SELECT name FROM student
ORDER BY age
UNION
SELECT grade FROM student
ORDER BY age;
为了避开语法的问题,有了下面的解决办法,使用子查询
SELECT * from
(SELECT name FROM student
ORDER BY age) t1
UNION (all)
SELECT * from
(SELECT grade FROM student
ORDER BY age);
顺利通过,可是查看结果会发现,排序失效了。因为子查询规则是没有top语句(mysql中用limit代替),
排序不生效,再次修改:
SELECT * from
(SELECT name FROM student
ORDER BY age limit 0, 1000) t1
UNION (all)
SELECT * from
(SELECT grade FROM student
ORDER BY age limit 0, 1000);
成功!!!
最后,union和union all的差别是前者会忽略重复数据,后者不会。