【发布时间】:2020-11-06 06:20:34
【问题描述】:
我有 2 个如下表。我下面的代码是连接 2 个表(左连接)。问题是我必须两次做同样的加入。第一个连接发生在 log_no 和 LogNumber 上,它返回左表 (table1) 中的所有记录,以及右表 (table2) 中的匹配记录。第二个连接做同样的事情,但在 log_no 的子字符串上使用 LogNumber。例如,777 将与表 2 中的 777 匹配,777-A 没有匹配,但是当使用子字符串函数时,777-A 变为 777,这将在表 2 中匹配。
不是像下面那样创建 2 个单独的连接,而是如何用一个连接来覆盖这两种情况。代码如下:
# first join to match 1234-A (table 1) with 1234-A (table 2)
df5 = df5.join(df_app, trim(df5.LOG_NO) == trim(df_app.LogNumber), "left")\
.select (df5["*"], df_app["ApplicationId"])
df5 = df5.withColumnRenamed("ApplicationId","ApplicationId_1")
# second join with substring function, to match 777-C with 777,
# my string is longer than my examples, this is why I have a substring for the first 8 characters. I provided simple examples.
df5 = df5.join(df_app, substring(trim(df5.LOG_NO), 1, 8) == trim(df_app.LogNumber), "left")\
.select (df5["*"], df_app["ApplicationId"])
df5 = df5.withColumnRenamed("ApplicationId","ApplicationId_2")
【问题讨论】:
标签: apache-spark pyspark apache-spark-sql pyspark-dataframes