带有UNION的SQL ORDER BY

时间:2014-08-04 05:40:22

标签: mysql sql sql-order-by union

我尝试根据现有表格创建视图。 该表将如下:

+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| 1    | a1   | a2   | a3   |
| 2    | b1   | b2   | b3   |
| 3    | c1   | c2   | c3   |
| 4    | d1   | d2   | d3   |
| 5    | e1   | e2   | e3   |
| 6    | f1   | f2   | f3   |
+------+------+------+------+

结果视图应按以下方式包含行:

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 1    | a1   | a3   |
| 2    | a2   | a3   |
| 3    | b1   | b3   |
| 4    | b2   | b3   |
| 5    | c1   | c3   |
| 6    | c2   | c3   |
+------+------+------+

我的SQL查询如下所示:

(select col1 as "col 1",col2 as "col 2",col4 as "col 3" from t1)
union
(select col1 as "col 1",col3 as "col 2",col4 as "col 3" from t1)
order by "col 2","col 3"

order by似乎不起作用。我在order by

之后为我提供的任何别名获得相同的行顺序

提前致谢

6 个答案:

答案 0 :(得分:2)

您的MySQL实例很可能配置为treat double-quoted strings as string literals rather than quoted identifiers。如果您使用MySQL的本机反引号来分隔ORDER BY中的名称,you will get the expected result

(select col1 as "col 1",col2 as "col 2",col4 as "col 3" from t1)
union
(select col1 as "col 1",col3 as "col 2",col4 as "col 3" from t1)
order by `col 2`,`col 3`

答案 1 :(得分:1)

尝试:

select * from (
  (select col1 as col1,col2 as col2,col4 as col3 from t1)
  union
  (select col1 as col1,col3 as col2,col4 as col3 from t1)
) as t
order by t.col2,t.col3

在您的情况下,只有第二个查询会对结果进行排序。

答案 2 :(得分:0)

SELECT AId AS A1, BId AS S2, CId  AS S3 FROM(
    SELECT AId, BId, CId FROM TableName
    UNION
    SELECT AId, BId, CId FROM TableName
) AS T ORDER BY S2, S3 DESC

但为什么你需要在两个相同的记录集中使用联合?

答案 3 :(得分:0)

试试这个

(select col1 as c1,col2 as c2,col4 as c3 from t)
union
(select col1 as c1,col3 as c2,col4 as c3 from t)
order by c2,c3

Demo

答案 4 :(得分:0)

这应该这样做:

SELECT COL_1, COL_2, COL_3 
FROM ((SELECT COL1 AS COL_1, COL2 AS COL_2, COL4 AS COL_3 FROM T1) 
UNION (SELECT COL1 AS COL_1, COL3 AS COL_2 , COL4 AS COL_3 FROM T1)) 
ORDER BY COL_1, COL_2

或者只是这样:

(SELECT COL1 AS COL_1, COL2 AS COL_2, COL4 AS COL_3 FROM T1) 
UNION 
(SELECT COL1 AS COL_1, COL3 AS COL_2 , COL4 AS COL_3 FROM T1)
ORDER BY COL_1, COL_2

答案 5 :(得分:0)

您的order by指定两个常量字符串,而不是包含空格的列名。尝试

select col1, col2, col4 as col3 from t1
union
select col1, col3 as col2, col4 as col3 from t1
order by col2, col3

这仍然不会为你重新排序col1。