0

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.

1
  • 1
    Your inner select doesnt have FROM clause Commented Jul 9, 2018 at 14:59

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.