SQL选择语句列顺序与联合


SQL select statement column order with union

在联合表中是否有一种方法可以忽略首先选择列顺序并通过列名匹配记录?

举个例子:

// TEST1 table:
|  a  |  b  |
-------------
|  3  |  5  |
// TEST2 table:
|  b  |  a  |
-------------
|  4  |  9  |
select a, b from TEST1 union ( select b, a from TEST2)
// The result must be a table like the on below:
|  a  |  b  |
-------------
|  3  |  5  |
-------------
|  9  |  4  |
// BUT, actually is:
|  a  |  b  |
-------------
|  3  |  5  |
-------------
|  4  |  9  |
更新:

列的名称和编号是一样的,只是顺序不同,我不能改变第二次选择列的顺序。

我要求一种方法来忽略默认的sql联合行为,并告诉它匹配列名,而不是传递

的顺序

UNION没有这种功能。

你必须找到一个变通方法,例如:

select concat('a',a) as a, concat('b',b) as b from TEST1 union ( select concat('b',b) as b, concat('a',a) as a from TEST2)

你会得到这样的东西:

|  a  |  b  |
-------------
|  a3  |  b5  |
-------------
|  b4  |  a9  |

表中字段的顺序是无关的。在联合子查询中指定字段的顺序才是重要的。

当前有:

    select a, b from TEST1
union      |  |
    select b, a from TEST2)

而不是

    select a, b from TEST1
union      |  |
    select a, b from TEST2

字段排序在表定义中起作用的唯一情况是当您执行select *