[英]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.表 users 中的用户 id (id) 是表 stock 中列 current_owner 的外键约束。 I want to update a column named holdings in users table based on count of rows where users.id = stock.current_owner.我想根据users.id = stock.current_owner 的行数更新users 表中名为holds 的列。 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()根据用户和 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
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.