可否优化以下语句sql = "select date_j,count(*) from jiaoban_day group by date_j order by date_j desc" co.to_sql(sql) jg = cs.fetchall() data = {} for j in jg: sql = "select date_j,count(*) from personnal_note where id_person='{0}' and date_j='{1}'".format(id_person,j[0]) co.to_sql(sql) n = cs.fetchone() data[j[0]] = str(j[1]+n[0])
时间: 2024-03-18 15:40:02 浏览: 51
关于SQL语句的优化
可以进行如下优化:
1. 可以将两条 SQL 语句合并为一条,使用 JOIN 操作,避免多次查询数据库。
2. 可以使用 Pandas 库将查询结果转换为 DataFrame,然后进行聚合操作,避免使用 for 循环遍历查询结果。
下面是优化后的代码示例:
```python
import pandas as pd
sql = "SELECT jiaoban_day.date_j, COUNT(*) AS cnt1, COUNT(personnal_note.date_j) AS cnt2 \
FROM jiaoban_day \
LEFT JOIN personnal_note \
ON jiaoban_day.date_j = personnal_note.date_j \
AND personnal_note.id_person='{0}' \
GROUP BY jiaoban_day.date_j \
ORDER BY jiaoban_day.date_j DESC".format(id_person)
df = pd.read_sql(sql, co)
data = {}
for _, row in df.iterrows():
data[row['date_j']] = str(row['cnt1'] + row['cnt2'])
```
阅读全文