python - 嵌套 SQL 查询太慢

标签 python mysql

我有以下代码,在第一个查询的结果集循环中执行另一个查询 表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/

相关文章:

python - Windows 错误 0 "ERROR_SUCCESS"是什么意思?

python - SQLAlchemy导入错误: import _mysql

python - Matplotlib 极坐标图的反向径向轴

php - 如何使用 WAMP 登录 phpMyAdmin,用户名和密码是什么?

java - 无法在 Java 中循环 ResultSet

mysql - 为什么这个查询给出两个不同的结果?

mysql - 数据库模型和迁移说明

python - Python 游戏 - 添加选项 "Restart game"

python - Tweepy:Twitter 错误响应:状态代码 = 500

Python 礼仪 : Importing Modules