Sql 如何仅显示多个表中至少一个表上存在匹配项的记录?

Sql 如何仅显示多个表中至少一个表上存在匹配项的记录?,sql,apache-spark,apache-spark-sql,Sql,Apache Spark,Apache Spark Sql,我有几张桌子。我想加入反对党。我只想看到至少其中一个表上有匹配项的记录 insert into foo values (1), (2), (3), (4), (5), (6), (7), (8); insert into a values (1), (2), (3); insert into b values (3), (4), (5), (6); 期望输出: id id id 1 1

我有几张桌子。我想加入反对党。我只想看到至少其中一个表上有匹配项的记录

insert into foo values
  (1),
  (2),
  (3),
  (4),
  (5),
  (6),
  (7),
  (8);

insert into a values
  (1),
  (2),
  (3);

insert into b values
  (3),
  (4),
  (5),
  (6);
期望输出:

id      id      id
1       1       (null)
2       2       (null)
3       3       3
4       (null)  4
5       (null)  5
6       (null)  6   
通常,我会使用WHERE-EXISTS(例如:下文)来实现这一点,但SparkSQL不支持这一点。实现这一目标最有效的方法是什么?我更愿意依靠我的联接来确定结果,而不是过滤结果集。另外,我并不局限于使用SparkSQL,DataFrameAPI也很棒

select * 
from foo
left join a on foo.id = a.id
left join b on foo.id = b.id
where exists (select 1 from a x where foo.id = x.id)
or exists (select 1 from b x where foo.id = x.id)
;

您可以尝试
LEFT JOIN
,并在
where

SELECT * 
FROM foo 
LEFT JOIN a on foo.id  = a.id 
LEFT JOIN b on foo.id  = b.id 
WHERE a.id IS NOT NULL OR  b.id IS NOT NULL
ORDER BY foo.id
你很接近:

select * 
from foo left join
     a
     on foo.id = a.id left join
     b
     on foo.id = b.id
where a.id is not null or b.id is not null;

您需要使用过滤器进行
完全外部连接
左连接

select f.*, a.*, b.*
from foo f full outer join
     a
     on a.id = f.id full outer join
     b
     b.id = f.id
where a.id is not null or b.id is not null;

下面是使用DataFrame API的解决方案:

val foo = (1 to 8).toDF("id")
val a = Seq(1,2,3).toDF("id")
val b = Seq(3,4,5,6).toDF("id")


foo
.join(a,foo("id")===a("id"),"left")
.join(b,foo("id")===b("id"),"left")
.where(a("id").isNotNull or b("id").isNotNull)
.show()

+---+----+----+
| id|  id|  id|
+---+----+----+
|  1|   1|null|
|  2|   2|null|
|  3|   3|   3|
|  4|null|   4|
|  5|null|   5|
|  6|null|   6|
+---+----+----+

谢谢你的回复。我想知道使用左半连接是否更有意义。我担心
is not null
子句效率低下,因为我们将带回将被丢弃的数据。@Josh。你可以尝试两种方法,看看哪个更快。