SQL 如何为 UNION 构建“虚拟列”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39766336/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:53:58  来源:igfitidea点击:

How to build "dummy columns" for UNION?

sql

提问by Mike Pala

from what I understand "each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order." Well what if the first SELECT has more columns than the 2nd one can generate. Here's what I mean: let's say I want to

根据我的理解,“UNION 中的每个 SELECT 语句必须具有相同数量的列。列也必须具有相似的数据类型。此外,每个 SELECT 语句中的列必须具有相同的顺序。” 好吧,如果第一个 SELECT 的列比第二个可以生成的列多怎么办。这就是我的意思:假设我想要

SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country" from table2     

...let's say table 2 does not contain a column called "Continent" but for my needs it's fine for the records that come from table2 to have a blank or NULL in that column. I am using dashDB.

...假设表 2 不包含名为“Continent”的列,但根据我的需要,来自 table2 的记录在该列中具有空白或 NULL 是可以的。我正在使用 dashDB。

回答by Tim Schmelter

You can always add "virtual" columns:

您始终可以添加“虚拟”列:

SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country", NULL AS "Continent" from table2 

回答by Jim Macaulay


Hi,
You can use,


您好,
您可以使用,

 SELECT "City", "Country", "Continent" from table1  
UNION  
SELECT "City", "Country", ' ' as "Continent"  from table2

or

或者

 SELECT "City", "Country", "Continent" from table1  
    UNION  
    SELECT 

"City", "Country", NULL as "Continent"  from table2

It considers "Continent" as null in table2

它将表 2 中的“Continent”视为空