简体   繁体   中英

Column names for a table formed by a UNION

Given a couple of simple tables like so:

create table R(foo text);
create table S(bar text);

If I were to union them together in a query, what do I call the column?

select T.????
from (
    select foo
    from R
    union
    select bar
    from S) as T;

Now, in mysql, I can apparently refer to the column of T as 'foo' -- the name of the matching column for the first relation in the union. In sqlite3, however, that doesn't seem to work. Is there a way to do it that's standard across all SQL implementations?

If not, how about just for sqlite3?

Correction: sqlite3 does allow you to refer to T's column as 'foo' after all! Oops!

Try to give an alias to columns;

select T.Col1
from (
    select foo as Col1
    from R
    union
    select bar as Col1
    from S) as T;

or If the name of column is not necessary then T.* will be enough.

虽然没有拼写规则,但我们可以使用union查询中第一个子查询的列名来获取联合结果。

you only need column aliases only in first select (tested in SQl Server 2008 R2)

select T.Col1
from (
    select 'val1' as Col1
    union
    select 'val2'
    union
    select 'val3'     
) as T;

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