简体   繁体   中英

UNION ignores column names?

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要求按顺序选择它们。

Column names are only pertinent for the first part of the union to deifne the union columns. Other unions will join in the same order the columns are given from the first select and often have differn names. If you want want to relate the first column to the second column, You can't. However you can adjust your second select statment to put the columns in the correct order.

Union only looks at the number of columns, and their relative positions in the query string. it does NOT mix-match based on aliases or the source column names. eg You could have two completely different tables:

SELECT x,y FROM foo
UNION
SELECT p,q FROM bar

What should MySQL do in this case? return a single row

x,y,p,q

because none of the column names match? Nope. That'd be incorrect.

I'm not sure if this solves your problem, but you can use subqueries within the union to put the columns in the "right" order:

(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)

I realize the question is tagged MySQL, which doesn't support full outer join . If it did, you could do do the union all as:

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;

You can do this in MySQL. This assumes that none of your values are never 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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