SQL 由 UNION 形成的表的列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/320004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Column names for a table formed by a UNION
提问by Dan Homerick
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?
现在,在 mysql 中,我显然可以将 T 的列称为“foo”——联合中第一个关系的匹配列的名称。然而,在 sqlite3 中,这似乎不起作用。有没有办法做到这一点,这是所有 SQL 实现的标准?
If not, how about just for sqlite3?
如果没有,仅用于 sqlite3 怎么样?
Correction: sqlite3 does allow you to refer to T's column as 'foo' after all! Oops!
更正:sqlite3 确实允许您将 T 的列称为“foo”!哎呀!
回答by Ali Ers?z
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.* 就足够了。
回答by Shyam
Although there is no spelled rule, we can use the column names from the first subquery in the union query to fetch the union results.
虽然没有拼写规则,但我们可以使用联合查询中第一个子查询的列名来获取联合结果。
回答by Iman
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;