duanfei7508 2016-12-06 10:39
浏览 293
已采纳

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

I have these 2 tables below : users:

         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

I have successfully insert { user_pages aggregate of (7dexpf) flags} into users table (7dexpn) matching by user_pages (user_id) with users table (id) with this query

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;

But the query not update flag back to zero if u.7dexpn = 0

  • 写回答

1条回答 默认 最新

  • dongque1646 2016-12-06 10:44
    关注

    Use a LEFT JOIN with COALESCE() :

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果