简体   繁体   English

由UNION形成的表的列名

[英]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. 现在,在mysql中,我显然可以将T的列称为'foo' - 联合中第一个关系的匹配列的名称。 In sqlite3, however, that doesn't seem to work. 但是,在sqlite3中,这似乎不起作用。 Is there a way to do it that's standard across all SQL implementations? 有没有办法在所有SQL实现中做到这一点?

If not, how about just for sqlite3? 如果没有,那对于sqlite3怎么样?

Correction: sqlite3 does allow you to refer to T's column as 'foo' after all! 更正:sqlite3确实允许你将T的列称为'foo'毕竟! 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. 或者如果不需要列的名称那么T. *就足够了。

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

you only need column aliases only in first select (tested in SQl Server 2008 R2) 您只需要在第一个选择中使用列别名(在SQl Server 2008 R2中测试)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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