首页 > 解决方案 > 如何获取不在内部连接sql中的列,使用union all是很多时间

问题描述

我有 2 个具有相同列的表,并且它们具有如下内部联接,我正在尝试获取内部联接中未采用的列。我将在 spark-sql 代码中使用它。

select A.pension, B.pension
from Db1.table1 A, Db2.table2 B
where to_date(A.rdt) = '2019-06-20' and A.state = 'ohio' and A.empno= B.empno;

我曾尝试使用 UNION ALL,但花费的时间超过系统超时,没有添加子句。

select A.pension
from Db1.table1 A left outer join
     Db2.table2 B 
     on A.pension = B.pension
where B.pension is null
UNION ALL
select B.pension
from Db2.table2 A left outer join
     Db1.table1 B 
     on A.pension = B.pension
where A.pension is null;

我也尝试过使用完全外连接,也需要时间,查询没有运行。

select A.pension, B.pension
from Db1.table1 A full outer join
     Db2.table2 B
     on A.empno = B.empno
where to_date(A.rdt) = '2019-06-20' and A.state  = 'ohio' and A.pension = NULL or B.pension = NULL

rdt 在时间戳、养老金 int、empno int 中,

我们只想要内部连接没有选择的记录,输出必须是一个包含 A.pension、B.pension 列的表,只有这两列中不匹配的记录。

标签: sqljoinhiveapache-spark-sqlhql

解决方案


Full outer join使用过滤时很棘手。我建议在子查询中进行过滤:

select A.pension, B.pension
from (select A.*
      from Db1.table1 A
      where to_date(A.rdt) = '2019-06-20' and A.state  = 'ohio' 
     ) A full outer join
     Db2.table2 B
     on A.empno = B.empno
where A.pension = NULL or B.pension = NULL

推荐阅读