簡體   English   中英

Pyspark,連接,sql,外連接

[英]Pyspark, joins ,sql,outer join

我有這樣的要求...我想外部連接兩個表 A 和 B(例如),以便如果鍵匹配我的輸出應該有表 B 的值(不是 A 列值)Ex

A
a b
1 abc
2 fgh
3 xyz

B
a b
1 wer
6 uio

輸出

a b
1 wer
2 fgh
3 xyz
6 uio

這是一個優先級查詢。 您似乎想要來自b所有行,然后a基於第一列的來自a的不匹配行。

一種方法是union all

select b.*
from b
union all
select a.*
from a
where not exists (select 1 from b where b.a = a.a);

Pyspark 解決方案是使用full連接和coalesce

from pyspark.sql import functions as F

# Create dataframes
A = spark.createDataFrame(data=[[1, 'abc'], [2, 'fgh'], [3, 'xyz']], schema=['a', 'b'])
B = spark.createDataFrame(data=[[1, 'wer'], [6, 'uio']], schema=['a', 'b'])

# Rename column `b` to prevent naming collision 
A = A.select('a', F.col('b').alias('b_a'))
B = B.select('a', F.col('b').alias('b_b'))

# Full join on `a` keeps all entries from both dataframes
combined = A.join(B, on='a', how='full')

# Coalesce takes value from `b_b` if not null and `b_a` otherwise
combined = combined.withColumn('b', F.coalesce('b_b', 'b_a'))

# Drop unneeded helper columns
combined = combined.drop('b_b', 'b_a')

combined.show()

結果

+---+---+
|  a|  b|
+---+---+
|  1|wer|
|  2|fgh|
|  3|xyz|
|  6|uio|
+---+---+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM