【发布时间】:2021-11-14 06:22:36
【问题描述】:
这是我所拥有的:
-
Pandas 数据框(名为 df)
- 2 列:c1 和 c2
-
SQL 中的表(名为 sql_table)
- 3 列:c3、c4 和 c5
-
SQL 中的目标表(名为 target_table)
- 5 个空列:c1、c2、c3、c4 和 c5
-
c1(来自 df)可以与 c3(来自 sql_table)连接
-
c2(来自 df)可以与 c4(来自 sql_table)连接
df 中的所有记录都必须显示(暗示外连接)
INSERT INTO target_table (c1, c2, c3, c4, c5)
SELECT c1, c2, c3, c4,
CASE WHEN t1.c5 IS NOT NULL THEN t1.c5
WHEN t2.c5 IS NOT NULL THEN t2.c5
ELSE NULL END AS c5
FROM dataframe as df
LEFT JOIN sql_table AS t1 ON df.c1 = t1.c3
LEFT JOIN sql_table AS t2 ON df.c2 = t2.c4;
我知道这个查询(和语法)不正确,但这是一般的想法。
目前,我在 SQL 中有 3 个表:
- temp_target _table
- sql_table
- 目标表
到目前为止,我正在将 df(从 Python)导入 temp_target_table(通过 sqlalchemy)并手动执行连接(在 SQL 中)并将这些结果插入到 target_table 中。我想避免使用 temp_target_table。
【问题讨论】:
-
我相信你最好的选择是在 SQL 中使用临时表。你想要临时表有什么原因吗?
标签: python sql-server pandas sqlalchemy