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

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

但这并不奏效。


当前回答

为了添加到旧的主题,我使用了ROW_NUMBER(使用MS SQL)。这允许在union内排序(顺序)。 所以使用来自@BATabNabber的想法来分离联盟的每一半,而@Wodin将整个事情包装在一个选择中,我得到:

Select Id, Name, Age from
(
Select Id, Name, Age, 1 as Mainsort
 , ROW_NUMBER() over (order by age) as RowNumber
From Student
Where Age < 15

Union

Select Id, Name, Age, 2 as Mainsort
 , ROW_NUMBER() over (Order by Name) as RowNumber
From Student
Where Name like '%a%'
) as x
Order by Mainsort, RowNumber

所以调整,或省略,你想要的顺序,并添加下降,因为你认为合适。

其他回答

Select id,name,age
from
(
   Select id,name,age
   From Student
   Where age < 15
  Union
   Select id,name,age
   From Student
   Where Name like "%a%"
) results
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);

可以用这个:

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

只写

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

顺序被应用到完整的结果集

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

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

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

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