I have a user table which has columns user_id, update_time, etc and an action table, which has columns user_id, action and create_time table.
class User(models.Model): user_id = models.CharField(db_index = True, max_length = 255, unique = True, null = False) update_time = models.DateTimeField(db_index = True, default = timezone.now, null = True, blank = True) class Action(models.Model): user_id = models.CharField(db_index = True, max_length = 255, null = False) action = models.CharField(db_index = True, max_length = 15, unique = False, null = False) create_time = models.DateTimeField(db_index = True, auto_now_add = True, null = True) I want to save user's last active time in update_time column. I am getting many actions by many users per day. So I don't update user table update_time column while inserting an action. I update the update_time column by a background job, which finds the max of create_time of all actions corresponding to a user_id and update his update_time column in the user table.
The background job runs below code/query for this purpose. But the performance of this piece of code not so good. Can anyone help me optimize it, either a better MySQL query or even in a format of Django ORM query or any different strategy to do this overall thing?
days_limit = datetime.now() - timedelta(1) query = "UPDATE user a JOIN (SELECT user_id, MAX(create_time) AS last_create_time FROM user_action WHERE create_time >= %s GROUP BY user_id) b ON a.user_id = b.user_id SET a.update_time = last_create_time WHERE a.update_time < last_create_time" cursor = connection.cursor() print cursor.execute(query, [str(days_limit)])