mysql基于选择,基于当前行值更新多行

时间:2018-07-09 14:54:23

标签: php mysql mysqli

我想每小时从另一个名为visitors的表中基于count()更新表sessions

我到目前为止的代码:

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)

似乎在做些什么,但是当我简单地检查访问者在过去30天内的实际会话次数时,数字却不匹配。

1 个答案:

答案 0 :(得分:1)

使用相关查询:

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
                           )

如果要使用加入的奖励,则需要先计算总数

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