python - How can one optimize this MySQL count algorithm? -
i have 2 tables; 1 users , other records user actions. want count number of actions per user , record in users table. there ~100k user , following code takes 6 hours! there must better way!
def calculate_invites():
sql_db.execute("select id, uid users") row in sql_db: id = row['id'] uid = row['uid'] sql1 = "select count(1) actions uid = %s" sql_db.execute(sql1, uid) count_actions = sql_db.fetchone()["count(1)"] sql = "update users set count_actions=%s uid=%s" sql_db.execute(sql, (count_actions, uid))
you can 1 statement:
update users set count_actons = (select count(*) actions a.uid = users.uid)
no loop. no multiple queries. in sql can in sql. looping on rows want in database rather in application.
Comments
Post a Comment