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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘