SQL:没有完整列匹配的两个表的联合

SQL: Union of two tables which don't have full column match

我有一个 table_A,它有一组列 A1A2 和一个 table_b,它有一组列 B1B2

碰巧 A2=B1 但其余列不匹配(并且不应该匹配)。我想附加 table 所以我使用 UNION ALL

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

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"

是因为空值吗?

您需要将 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