我有以下代码,在第一个查询的结果集循环中执行另一个查询 表1有35K条记录,而表2有4M
db = MySQLdb.connect("localhost","root","root","test" )
cursor1 = db.cursor(MySQLdb.cursors.DictCursor)
cursor2 = db.cursor(MySQLdb.cursors.DictCursor)
sql = 'select * from table1 limit 2'
cursor1.execute(sql)
results = cursor1.fetchall()
for row in results:
sql2 = 'select * from table2 where t1 = '+row['t1']
cursor2.execute(sql2)
result2 = cursor2.fetchall()
for row2 in result2
#do something
对于每一次迭代和每一次查询,这个过程似乎都在等待。我尝试使用 cProfile 进行分析并得到以下输出之一
ncalls tottime percall cumtime percall filename:lineno(function)
3 21.529 7.176 21.529 7.176 connections.py:274(query)
如何调试这个问题?我对 python 很陌生。
最佳答案
在 Web 应用程序中嵌套查询从来都不是一个好主意。正如您所发现的,它会降低性能。
尝试使用连接表 1 和表 2 的单个查询。然后,以编程方式跟踪父数据何时更改以处理换行符或显示更改。
关于python - 嵌套 SQL 查询太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377422/