请优化mysql查询语句sql = '''select id,isUpdate,zhize_name from zhize_0 where user_name='{0}' and isDelete='有效' ''' co.to_sql(sql) jg = cs.fetchall() jg1 = [] for j in jg: sql = "select count(*) from zhize_xiangmu where id_zhize='{}'".format(j[0]) co.to_sql(sql) jgx = cs.fetchone() jg1.append([j[0],j[1],j[2],jgx[0]])
时间: 2023-07-16 16:13:34 浏览: 282
可以考虑将两个查询合并成一个,使用JOIN语句。这样可以减少数据库连接的次数,从而提高查询效率。
优化后的SQL语句如下:
```
SELECT z.id, z.isUpdate, z.zhize_name, COUNT(x.id_zhize) AS count_xiangmu
FROM zhize_0 z
LEFT JOIN zhize_xiangmu x ON z.id = x.id_zhize
WHERE z.user_name='{0}' AND z.isDelete='有效'
GROUP BY z.id, z.isUpdate, z.zhize_name
```
然后可以直接执行这个SQL语句并获取结果,不需要再进行循环查询了。
优化后的Python代码如下:
```
sql = "SELECT z.id, z.isUpdate, z.zhize_name, COUNT(x.id_zhize) AS count_xiangmu " \
"FROM zhize_0 z " \
"LEFT JOIN zhize_xiangmu x ON z.id = x.id_zhize " \
"WHERE z.user_name='{0}' AND z.isDelete='有效' " \
"GROUP BY z.id, z.isUpdate, z.zhize_name".format(user_name)
co.to_sql(sql)
jg = cs.fetchall()
jg1 = [list(j) for j in jg]
```
阅读全文