【问题标题】:How to use an SQL query with join on the result of another SQL query executed before?如何将 SQL 查询与之前执行的另一个 SQL 查询的结果结合使用?
【发布时间】:2021-08-17 11:41:05
【问题描述】:

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

例如: 我有 table1,其中有一个 codecolumn,table2 中有相同的代码列 现在我正在匹配两列的值,并加入表 2 中对应于代码的列“区域”和 table1 中的列“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 在匹配代码列时,无论我在哪里获得区域为无,我都需要使用 table1 中的 pincode 列和 table3 中的 pincode 列再次从 table3.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)

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

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

这是查找该区域的两种方法

期望的结果应该是:

什么是正确的解决方案? 谢谢你

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。
  • 嗨。我添加了更多信息来解释。我希望它有所帮助。谢谢@GordonLinoff
  • 您的附加信息是所需的结果。虽然这很好,但如果没有用于生成它的输入和表定义,它就毫无用处。请以文本形式添加表格定义和测试数据 - 无图像(参见Why no Images)或更好地创建fiddle

标签: python sql database postgresql join


【解决方案1】:

看起来您的 query2 需要 where 子句和子查询,因为错误消息应该减少到您尝试传递给外部查询的列。 query2 应该是这样的:

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

【讨论】:

  • 嗨,查询有效,但我没有得到想要的结果。也许我的查询对于我想要的结果不正确。 @Jayvee
猜你喜欢
  • 2018-10-17
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多