如何对之前执行的另一个SQL查询的结果使用带有join的SQL查询?

2024-03-28 22:39:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对上一个SQL查询的结果使用SQL查询,但无法使用。 我正在创建一个python脚本并使用postgresql。 我有3个表,需要从中匹配不同的列并连接数据,但一次只使用2个表

例如: 我有表1,其中有一个codecolumn,表2中有一列相同的代码 现在,我正在匹配这两列的值,并将表2中对应于代码的列“area”和表1中的列“pincode”连接起来

为此,我使用了以下有效的查询:

'''
select 
table1.code,table2.code,table2.area,table1.pincode 
from 
table1 left join table2
 ON 
table1.code=table2.code  
order by table1.row_num '''

我得到了结果,但在这个数据中,有一些数据的面积值返回为无 在匹配代码列时,无论我在哪里将区域设置为None,我都需要使用表1中的pincode列和表3中的pincode列再次从表3.area中找到相应的区域

因此,我使用了以下查询:

'''
select 
table1.code,table3.area,table1.pincode 
from 
table1 left join table3 
ON 
table1.pincode=table3.pincode 
IN (
select 
table1.code,table2.code,table2.area,table1.pincode 
from 
table1 left join table2
ON 
table1.code=table2.code  
where table2.area is NULL
order by table1.row_num '''  

我得到了以下错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) subquery has too many columns

我的python代码如下所示:

import psycopg2
from sqlalchemy import create_engine

engine=create_engine('postgresql+psycopg2://credentials')
conn=engine.connect()

query = '''
select 
table1.code,table2.code,table2.area,table1.pincode 
from 
table1 left join table2
 ON 
table1.code=table2.code  
order by table1.row_num '''

area=conn.execute(query)
area_x=area.fetchall()
for i in area_x:
    print(i)

query2 = select 
table1.code,table3.area,table1.pincode 
from 
table1 left join table3 
ON 
table1.pincode=table3.pincode 
IN (
select 
table1.code,table2.code,table2.area,table1.pincode 
from 
table1 left join table2
 ON 
table1.code=table2.code  
where table2.area is NULL
order by table1.row_num '''  

area=conn.execute(query2)
area_x=area.fetchall()
for i in area_x:
    print(i)

这是我的第一个查询返回数据的方式:

enter image description here

当我无法匹配代码列时,我从表2中的area列中获得None值,当area值为None时,我必须应用另一个查询来查找该数据 现在我必须将table1.pincode中的数据与table3.pincode中的数据进行匹配,以找到table3.area并用table3.area替换None值

以下是找到该区域的两种方法

预期结果应为:

enter image description here

正确的解决方案是什么?? 多谢各位


1条回答
网友
1楼 · 发布于 2024-03-28 22:39:50

看起来您的查询2需要where子句,并且子查询(根据错误消息)应该减少到您试图传递给外部查询的列。查询2应该是这样的:

query2 = 
select 
table1.code,table3.area,table1.pincode 
from 
table1 left join table3 
ON 
table1.pincode=table3.pincode 
WHERE table1.code
IN (
select 
table1.code
from 
table1 left join table2
 ON 
table1.code=table2.code  
where table2.area is NULL

相关问题 更多 >