Silver Ringvee
Silver Ringvee

Reputation: 5535

mysql update multiple rows based on select, based on current row value

I want to update my table visitors once an hour based on the count() from another table called sessions.

The code I have so far:

UPDATE visitors
INNER JOIN sessions 
   on visitors.visitor_ID = sessions.visitor_ID
SET visitors.last_30_day_sessions = (select count(sessions.session_ID) 
                                     where sessions.session_timestamp >= NOW() - INTERVAL 30 DAY)

It seems to be doing something but the numbers don't match when I simply check the number of sessions the visitor actually made in the past 30 days.

Upvotes: 0

Views: 1091

Answers (1)

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48197

Use correlated query:

UPDATE visitors
SET last_30_day_sessions = ( SELECT count(session_ID) 
                             FROM sessions
                             WHERE visitors.visitor_ID = sessions.visitor_ID
                               AND sessions.session_timestamp >= NOW() - INTERVAL 30 DAY
                           )

As a bonus if you want use join you need calculate the totals first

UPDATE visitors V
JOIN (SELECT visitor_ID, count(session_ID) session_count
      FROM sessions
      WHERE session_timestamp >= NOW() - INTERVAL 30 DAY
      GROUP BY visitor_ID
     ) s
   ON v.visitor_ID = s.visitor_ID
SET v.last_30_day_sessions  = s.session_count

Upvotes: 1

Related Questions