我有两个表的两个列表及其键列
keycol1 = [col1,col2]
keycol2 = [col3,col4]
我想用这两个列作为连接条件构建一个sql查询
for column1,column2 in zip(keycol1,keycol2):
join = "table1."+ column1 + " = " + "table2." + column2 and
qry = "select * from table1 join table2 on " + join
但最后这给了我额外的and
。如何避免呢?
预期查询:
select * from table1 join table2 on table1.col1 = table2.col3 and table1.col2 = table2.col4
答案 0 :(得分:2)
这是一种方式。
' and '.join()
<强>解释强>
答案 1 :(得分:1)
您也可以使用map
功能以及join
:
keycol1 = ['col1', 'col2']
keycol2 = ['col3', 'col4']
for column1,column2 in zip(keycol1,keycol2):
joined = " and ".join(map(lambda c: "table1."+ c[0] + " = " + "table2." + c[1], zip(keycol1, keycol2)))
qry = "select * from table1 join table2 on " + joined
print(qry)
输出:
select * from table1 join table2 on table1.col1 = table2.col3 and table1.col2 = table2.col4