小编典典

SQL:两个不具有完整列匹配项的表的并集

sql

我有一个table_A具有一组列的A1A2和表-B其中有一组列B1B2

碰巧发生了,A2=B1但是其余的列不匹配(并且不应该匹配)。我想追加表格,以便使用UNION ALL

对于不匹配的列,我null as COLUMN_NAMEUNION语句的两边使用,

CREATE VIEW MY_VIEW AS 
SELECT
TABLE_A.A1,
TABLE_A.A2,
null as B2
from TABLE_A
union all
SELECT 
null as A1,
TABLE_B.B1 as A2,
TABLE_B.B2 as B2
from TABLE_B;

输出以下错误:

Error report: SQL Error: ORA-01790: expression must have same datatype as corresponding expression 01790. 00000 - "expression must have same datatype as corresponding expression"

是因为空值吗?


阅读 183

收藏
2021-04-28

共1个答案

小编典典

您需要在上层将NULL显式转换为适当的类型SELECT

CREATE VIEW MY_VIEW AS 
SELECT
TABLE_A.A1,
TABLE_A.A2,
CAST(null AS <type_of_TABLE_B_B2>) as B2
from TABLE_A
union all
SELECT 
null,
TABLE_B.B1,
TABLE_B.B2
from TABLE_B;

至于 @evilive 说的替代方法,您可以将固定值用作 VARCHAR的
空字符串('')或将NUMBER用作零,但我认为显式强制转换是更好的解决方案,因为它很明显并且不会引起意外

SQLFiddle

2021-04-28