Why does
select 1 as a, 2 as b
union all
select 20 as b, 10 as a
returns
a b
1 2
20 10
instead of
a b
1 2
10 20
?
Is there a way to make union
match column names?
不,UNION 需要按顺序选择它们。
列名仅与联合的第一部分相关,以定义联合列。其他联合将按照从第一个选择中给出的列的相同顺序加入,并且通常具有不同的名称。如果您想将第一列与第二列相关联,则不能。但是,您可以调整您的第二个 select 语句以将列按正确的顺序排列。
Union 仅查看列数及其在查询字符串中的相对位置。它不会基于别名或源列名称进行混合匹配。例如,您可以有两个完全不同的表:
SELECT x,y FROM foo
UNION
SELECT p,q FROM bar
在这种情况下 MySQL 应该怎么做?返回单行
x,y,p,q
因为没有列名匹配?没有。那是不正确的。
我不确定这是否能解决您的问题,但您可以使用 中的子查询union
将列按“正确”顺序排列:
(select a, b from (select 1 as a, 2 as b) t)
union all
(select a, b from (select 20 as b, 10 as a) t)
我意识到这个问题被标记为 MySQL,它不支持full outer join
. 如果是这样,你可以这样做union all
:
select coalesce(t1.a, t2.a) as a, coalesce(t1.b, t2.b) as b
from (select 1 as a, 2 as b) t1 full outer join
(select 20 as b, 10 as a) t2
on 0 = 1;
您可以在 MySQL 中执行此操作。这假设您的任何值都不是 NULL:
select coalesce(t1.a, t2.a) as a, coalesce(t1.b, t2.b) as b
from (select 1 as a, 2 as b union all select NULL, NULL) t1 join
(select 20 as b, 10 as a union all select NULL, NULL) t2
on (t1.a is null or t2.a is null) and coalesce(t1.a, t2.a) is not null