简体   繁体   English

SQL:如何按字母顺序排列工会?

[英]SQL: How to order a union alphabetically?

This is a slightly strange use case admittedly, but how do you order the results of a simple union like this alphabetically? 诚然,这是一个有点奇怪的用例,但是您如何按字母顺序对简单联合的结果进行排序?

select name 
from Reviewer
union
select model
from Car; 

Ironically, in many databases, your query would return the values in alphabetical order. 具有讽刺意味的是,在许多数据库中,查询将按字母顺序返回值。 The sorting is done during the duplicate removal for union . 在对union进行重复删除期间,将完成排序。

Of course, you can't depend on that. 当然,您不能依靠它。 So, you should include an order by clause: 因此,您应该包括一个order by子句:

select name 
from Reviewer
union
select model
from Car
order by name;

The order by applies to the complete union . order by适用于完整的union The column name comes from the first subquery. 列名称来自第一个子查询。

select val
from (
  select name as val 
  from Reviewer

  union

  select model as val
  from Car
) as x
order by val

Here is how to set alias and ORDER BY : 这是设置aliasORDER BY

SELECT 
  name AS NameModel
FROM Reviewer
UNION
SELECT  
  model AS NameModel
from Car
ORDER BY 
 NameModel;

The ORDER BY is evaluated after UNION . UNION之后评估ORDER BY

your sql : 您的sql:

select name 
from Reviewer
union
select model
from Car;

Answer 1 : 答案1:

select name from Reviewer
union
select model from Car
order by name;

Answer 2 : 答案2:

select * from
    (select name "id" from Reviewer
    union
    select model from Car) x
order by x.id;
select val
from (
  select name as val 
  from Reviewer

  union

  select model as val
  from Car
) as x
order by val

My answer and above both are same. 我的回答和上面的都是一样的。 In SQL, we can write in different ways. 在SQL中,我们可以用不同的方式编写。

We can also ignore as operator. 我们也可以忽略as运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM