简体   繁体   English

如何使用列别名在 SQL 中使用 UNION 排序?

[英]How to ORDER BY with UNION in SQL with column ALIASES?

Here is my very simple MYSQL request:这是我非常简单的 MYSQL 请求:

(SELECT start, name, id, info FROM `table1`)
UNION
(SELECT end, name, id, info FROM `table1`)

I want to sort the result by 1st column and I guessed I need to use aliases:我想按第一列对结果进行排序,我猜我需要使用别名:

(SELECT start as mydate, name, id, info FROM `table1`)
UNION
(SELECT end as mydate, name, id, info FROM `table1`)
ORDER BY mydate

I was surprised that MYSQL threw this error:我很惊讶 MYSQL 抛出这个错误:

 "Unknown column 'mydate' in 'where clause'" 

I ended with this working bad practice:我以这种糟糕的做法结束了:

(SELECT start, name, id, info FROM table1)
UNION
(SELECT end, name, id, info FROM table1)
ORDER BY 1

source: https://www.mysqltutorial.org/sql-union-mysql.aspx来源: https://www.mysqltutorial.org/sql-union-mysql.aspx

But I would like to understand my error !但我想了解我的错误!

Use a nested query.使用嵌套查询。

SELECT q.* 
  FROM (
              SELECT start as mydate, name, id, info FROM `table1`
              UNION ALL
              SELECT end as mydate, name, id, info FROM `table1`
       ) AS q
 ORDER BY q.mydate

The inner query builds up your result set and the outer one orders it.内部查询构建您的结果集,外部查询对其进行排序。 The MySQL query planner is reasonably smart about optimizing this sort of thing. MySQL 查询规划器在优化这类事情方面相当聪明。

By the way UNION removes duplicates and UNION ALL does not.顺便说一句, UNION会删除重复项,而UNION ALL不会。

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

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