在另一个 spark sql 查询中使用 PySpark Dataframe 列

Use PySpark Dataframe column in another spark sql query

我有一种情况,我正在尝试查询 table 并将该查询的结果(数据帧)用作另一个查询的 IN 子句。

从第一个查询中我得到以下数据框:

+-----------------+
|key              |
+-----------------+
|   10000000000004|
|   10000000000003|
|   10000000000008|
|   10000000000009|
|   10000000000007|
|   10000000000006|
|   10000000000010|
|   10000000000002|
+-----------------+ 

现在我想 运行 像下面这样的查询,动态使用该数据帧的值而不是对值进行硬编码:

spark.sql("""select country from table1 where key in (10000000000004, 10000000000003, 10000000000008, 10000000000009, 10000000000007, 10000000000006, 10000000000010, 10000000000002)""").show()

我尝试了以下方法,但是没有用:

df = spark.sql("""select key from table0 """)
a = df.select("key").collect()
spark.sql("""select country from table1 where key in ({0})""".format(a)).show()

有人可以帮助我吗?

您应该在两个数据框之间使用(内部)连接来获取您想要的国家/地区。看我的例子:

# Create a list of countries with Id's
countries = [('Netherlands', 1), ('France', 2), ('Germany', 3), ('Belgium', 4)]

# Create a list of Ids
numbers = [(1,), (2,)]  

# Create two data frames
df_countries = spark.createDataFrame(countries, ['CountryName', 'Id'])
df_numbers = spark.createDataFrame(numbers, ['Id'])

数据框如下所示:

df_countries:

+-----------+---+
|CountryName| Id| 
+-----------+---+
|Netherlands|  1|
|     France|  2|
|    Germany|  3|
|    Belgium|  4|
+-----------+---+

df_numbers:
+---+
| Id|
+---+
|  1|
|  2|
+---+

您可以通过以下方式加入他们:

countries.join(numbers, on='Id', how='inner')

导致:

+---+-----------+
| Id|CountryName|
+---+-----------+
|  1|Netherlands|
|  2|     France|
+---+-----------+

希望一切都解决了!