Thursday, 30 August 2018

Update a MySQL table with the values ​​of another table based on the match of id

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 am trying to insert { user_pages aggregate of (7dexpf) flags} into users table (7dexpn) matching by user_pages (user_id) with users table (id)
Expected results should be:
users:
         id 7dexpn
=========== ==========
          1 0
          2 1
          3 3


You want to aggregate the values in user_pages and then assign them. I would do:
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;

0 comments:

Post a Comment