(SELECT `size`, `type` FROM `table` WHERE `type`='a' ORDER BY `size` ASC)
UNION ALL
(SELECT `size`,`type` FROM `table` WHERE `type`='b' ORDER BY `size` DESC)
为什么这个查询不能正常工作?它将结果数组分为类型'a',然后键入'b',但在类型'a'结果中,它们不按大小排序(大小是正bigint)。
有什么建议吗? :)
答案 0 :(得分:7)
除非您使用order by
子句(或在MySQL group by
子句中),否则不会对查询结果进行排序。试试这个就可以得到你想要的东西:
(SELECT `size`, `type` FROM `table` WHERE `type`='a')
UNION ALL
(SELECT `size`,`type` FROM `table` WHERE `type`='b')
order by type,
(case when `type` = 'a' then size end) asc,
(case when `type` = 'b' then size end) desc;
子查询上的排序子句通常被忽略(例外情况是limit
时)。而且,即使不被忽略也可能对外部查询没有影响。
实际上,完全忘记union all
:
select size, `type`
from table
where type in ('a', 'b')
order by type,
(case when `type` = 'a' then size end) asc,
(case when `type` = 'b' then size end) desc;
type
子句中的第一个order by
是不必要的,但我认为它使订购的目的更清晰。