1

我有 2 张桌子;一个是用户,另一个记录用户操作。我想计算每个用户的操作数并将其记录在用户表中。大约有 10 万用户,下面的代码需要 6 个小时!一定会有更好的办法!

def 计算邀请():

sql_db.execute("SELECT id, uid FROM users")

for row in sql_db:
    id = row['id']
    uid = row['uid']

    sql1 = "SELECT COUNT(1) FROM actions WHERE uid = %s"
    sql_db.execute(sql1, uid)
    count_actions = sql_db.fetchone()["COUNT(1)"]

    sql = "UPDATE users SET count_actions=%s WHERE uid=%s"
    sql_db.execute(sql, (count_actions, uid))
4

2 回答 2

5

您可以将这一切作为一个语句来完成:

update users
    set count_actons = (select count(*) from actions a where a.uid = users.uid)

没有for循环。没有多个查询。在 SQL 中执行您可以在 SQL 中执行的操作。通常,循环遍历行是您想要在数据库中而不是在应用程序中执行的操作。

于 2013-05-18T19:24:49.630 回答
1

仅作为替代方案提供,因为戈登的回答可能更快:

update users
from (
   select uid, count(*) as num_actions
   from actions
   group by uid
   ) x
set count_actions = x.num_actions
where users.uid=x.uid
于 2013-05-18T19:30:16.543 回答