当数据来自许多选择和联合在一起时,是否有可能进行排序?如

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

但这并不奏效。


当前回答

为什么不用TOP X呢?

SELECT pass1.* FROM 
 (SELECT TOP 2000000 tblA.ID, tblA.CustomerName 
  FROM TABLE_A AS tblA ORDER BY 2) AS pass1
UNION ALL 
SELECT pass2.* FROM 
  (SELECT TOP 2000000 tblB.ID, tblB.CustomerName 
   FROM TABLE_B AS tblB ORDER BY 2) AS pass2

TOP 2000000是一个任意的数字,它大到足以捕获所有的数据。根据您的要求进行调整。

其他回答

可以用这个:

Select id,name,age
From Student
Where age < 15
Union ALL
SELECT * FROM (Select id,name,age
From Student
Where Name like "%a%")

顺序顺序应用在并集之后,所以 在语句的末尾添加一个order by子句:

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like '%a%'
Order By name

要将ORDER BY或LIMIT子句应用于单个SELECT,请将SELECT子句插入圆括号内:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

为了使排序只适用于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

其他两个答案都是正确的,但我认为值得注意的是,我陷入困境的地方是没有意识到你需要按别名排序,并确保两个选择的别名是相同的…所以

select 'foo'
union
select item as `foo`
from myTable
order by `foo`

请注意,我在第一个选择中使用单引号,而在其他选择中使用反引号。

这样就能得到你需要的排序。