![](/img/trans.png)
[英]How to use join on 3 tables with conditions in pyspark? (Multiple tables)
[英]Join tables in Pyspark with "conditional" conditions
我有两个要加入的表:
表十:
国家 | 城市 | 用户 |
---|---|---|
美国 | 波士顿 | 大卫 |
美国 | 迈阿密 | 约翰 |
法国 | 巴黎 | 彼得 |
表 Y:
国家 | 细节 | 价值 | ID |
---|---|---|---|
美国 | 城市 | 波士顿 | 1 |
美国 | 无效的 | 无效的 | 2 |
法国 | 无效的 | 无效的 | 3 |
这是我想要的输出:
国家 | ID | 城市 | 用户 |
---|---|---|---|
美国 | 1 | 波士顿 | 大卫 |
美国 | 2 | 无效的 | 大卫 |
美国 | 2 | 无效的 | 约翰 |
法国 | 3 | 无效的 | 彼得 |
我在 SQL 中得到这个的方法是:
select country, id, city, user
from X
join Y
on x.country = y.country
and if(y.detail='city', x.city=y.value, TRUE)
我怎样才能进入 pyspark?
您可以使用下面的代码执行此操作,但是我必须选择y.value
并将其别名为 city 以获得您的示例输出。
d1 = [
('USA', 'Boston', 'David'),
('USA', 'Miami', 'John'),
('France', 'Paris', 'Peter')
]
d2 = [
('USA', 'city', 'Boston', 1),
('USA', None, None, 2),
('France', None, None, 3)
]
x = spark.createDataFrame(d1, ['country', 'city', 'user'])
y = spark.createDataFrame(d2, ['country', 'detail', 'value', 'id'])
cond = (x.country == y.country) & (when(y.detail == 'city', x.city == y.value).otherwise(F.lit(True)))
x.join(y, on=cond).select(x.country, y.id, y.value.alias('city'), x.user).orderBy('id').show()
+-------+---+------+-----+
|country| id| city| user|
+-------+---+------+-----+
| USA| 1|Boston|David|
| USA| 2| null|David|
| USA| 2| null| John|
| France| 3| null|Peter|
+-------+---+------+-----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.