通过id匹配条件,根据另一个更新一个MySQL表值

时间:2016-12-06 10:39:01

标签: php mysql

我有以下两个表格: 用户:

         id 7dexpn
=========== ==========
          1 0
          2 0
          3 0


user_pages:
        id     user_id 7dexpf
========== =========== ==========
       99           1 0
       98           2 1
       97           3 1
       96           3 1
       95           3 1
       94           2 0

我已成功将{user_pages聚合的(7dexpf)标志}插入到user_pages(user_id)与users表(id)匹配的users表(7dexpn)中 使用此查询

update users u join
       (select user_id, count(*) as cnt
        from user_pages 
        where `7dexpf` = 1
        group by user_id
       ) uu
       on uu.user_id = u.id
    set u.`7dexpn` = uu.cnt;

但是如果u。7dexpn = 0

,查询不会将标志更新回零

1 个答案:

答案 0 :(得分:0)

LEFT JOINCOALESCE()

一起使用
UPDATE users u 
LEFT JOIN
     (SELECT user_id, COUNT(*) as cnt
      FROM user_pages 
      WHERE `7dexpf` = 1
      GROUP BY user_id
     ) uu
 ON uu.user_id = u.id
SET u.`7dexpn` = COALESCE(uu.cnt,0);