简体   繁体   中英

Populating a Column in a Table Based on Count of Rows in Another Table

I have two tables namely users and stock. User id (id) in table users is a foreign key constraint on column current_owner in the table stock. I want to update a column named holdings in users table based on count of rows where users.id = stock.current_owner. I tried the following query but it doesn't seem to work.

ALTER TABLE users ADD holdings INT UNSIGNED AS (COUNT * FROM stock WHERE stock.current_owner = users.id)

I need help with this query. Thanks

You need two queries

add the column using alter

  ALTER TABLE users ADD holdings INT UNSIGNED;

popolate the columns using Update based on a join between user and a subquery for count()

  UPDATE users 
  INNER JOIN (
    select current_owner, count(*) mycount
    from stock 
    GROUP BY current_owner
  ) t ON t.current_owner = users.id 
  SET user.holdings = t.mycount
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM