当数据来自许多选择和联合在一起时,是否有可能进行排序?如
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
如何按名称对此查询进行排序?
我试过了
Select id,name,age
From Student
Where age < 15 or name like "%a%"
Order by name
但这并不奏效。
为了使排序只适用于UNION中的第一个语句,你可以把它放在一个带有UNION ALL的子选择中(这两个在Oracle中都是必要的):
Select id,name,age FROM
(
Select id,name,age
From Student
Where age < 15
Order by name
)
UNION ALL
Select id,name,age
From Student
Where Name like "%a%"
或者(针对Nicholas Carey的评论)你可以保证顶部的SELECT是有序的,结果显示在下面的SELECT上面,就像这样:
Select id,name,age, 1 as rowOrder
From Student
Where age < 15
UNION
Select id,name,age, 2 as rowOrder
From Student
Where Name like "%a%"
Order by rowOrder, name