【问题标题】:Spark SQL : filtering a table on records which appear in another table (two columns)?Spark SQL:过滤出现在另一个表(两列)中的记录的表?
【发布时间】:2021-06-03 14:59:14
【问题描述】:

我有几个表,我想根据另一个表中是否存在两列来过滤其中一个表中的行。各表数据如下

Table1:一个哈希值可以关联多篇文章;一篇文章可以关联多个哈希

User Hash Article Name
Hash1 Article1
Hash1 Article2
Hash2 Article1
Hash3 Article3

Table2 : 每个用户哈希都与一个用户 ID 唯一关联

User Hash User ID
Hash1 ID1
Hash2 ID2
Hash3 ID3

表 3:每个文章名称都与文章编号唯一关联

Article Name Article number
Article1 Number1
Article2 Number2
Article3 Number3

表4

User ID Article Number OtherField
ID1 Number1 Misc1
ID2 Number2 Misc2
ID3 Number3 Misc3

我想在表 4 中保留组合(用户 ID、文章编号)存在于表 1 中的行(作为用户哈希和文章名称)。所以在这个例子中,我想得到以下结果:

User ID Article Number OtherField
ID1 Number1 Misc1
ID3 Number3 Misc3

在 Spark SQL 中执行此操作的最佳方法是什么?我已经尝试过使用 JOIN,但我正在为有两个条件而苦苦挣扎,我希望这两个条件都在一行中有效。

在我的示例中,ID2 和 Number2 都在 Table1 中,但不在同一行,所以我想从 Table4 中过滤掉这一行。

我希望问题足够清楚。提前致谢!

【问题讨论】:

  • 如果您已经将数据框转换为表,您应该考虑使用 SQL 的 EXISTS 子查询进行过滤。

标签: sql apache-spark join apache-spark-sql filtering


【解决方案1】:

你可以做一个半连接:

select * 
from table4 
left semi join (
    select * from table1 
    join table2 using (`User Hash`) 
    join table3 using (`Article Name`)
) using (`User ID`, `Article Number`)

+-------+--------------+----------+
|User ID|Article Number|OtherField|
+-------+--------------+----------+
|    ID1|       Number1|     Misc1|
|    ID3|       Number3|     Misc3|
+-------+--------------+----------+

或者等效地,where exists:

select * 
from table4 
where exists (
    select * from table1 
    join table2 using (`User Hash`) 
    join table3 using (`Article Name`) 
    where `User ID` = table4.`User ID` 
    and `Article Number` = table4.`Article Number`
)

【讨论】:

  • 非常感谢!哪里存在通常比做半连接更有效?
  • 它们实际上是相同的。如果您使用explain检查查询计划,您可以确认它们应该是相同的。
【解决方案2】:

如果我理解正确,这只是一堆连接:

select t2.userid, t3.articlenumber
from table1 t1 join
     table2 t2
     on t1.userhash = t2.userhash join
     table3 t3
     on t3.articlename = t1.articlename;

【讨论】:

  • 不,这不是关于加入我知道怎么做的前 3 个表,而是关于根据表 1 中是否存在相应记录来过滤表 4 的值。
猜你喜欢
  • 1970-01-01
  • 2016-06-04
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2021-01-26
相关资源
最近更新 更多