SQL:两个没有完整列匹配的表的并集

标签 sql oracle union

我有一个 table_A,其中有一组列 A1A2 和一个 table_b,其中有一组列 B1 ,B2

碰巧 A2=B1 但其余列不匹配(也不应该匹配)。我想附加表格,因此我使用 UNION ALL

对于不匹配的列,我在 UNION 语句两侧使用 null 作为 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"

是因为空值吗?

最佳答案

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

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

关于SQL:两个没有完整列匹配的表的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800482/

相关文章:

oracle - 在Oracle中查找存储过程的依赖元素

oracle - ORA-02303 : cannot drop or replace a type with type or table dependents

database - 如何查找和跟踪 Oracle 警报日志

MySql - 跨不同服务器的联合

mysql - 使用 "Union distinct"构造时保留子查询中记录的顺序

sql - 让 Oracle 将 OR 连接谓词转换为 UNION ALL 操作

mysql - 我可以将 Unique 约束和 Not Null 约束设置为 SQL 中的同一列吗?

Java derby 数据库不工作

PHP - SQL 脚本创建器

sql - 如何修复SQLite3::SQLException: near “to” : syntax error: SELECT “” .* FROM “” WHERE “” .“” = ? AND (to < '[Time.now]' ) LIMIT ? OFFSET?