从其他表值的计算中向表中添加mysql列

时间:2012-03-07 05:36:42

标签: mysql sql

我有两个表user_showscomments。它们都有一个共同的密钥id

我希望在user_shows中有一个列,它会在user_shows.id = comments.id时将评论数存储在评论表中。我试过了,想出了类似的东西:

ALTER TABLE user_shows 
ADD num_comments INT(4) AS (SELECT id 
                              FROM comments, 
                                   user_shows 
                             WHERE comments.id = user_shows.id)

......但这不起作用。

2 个答案:

答案 0 :(得分:4)

你必须写两个单独的查询: -

ALTER TABLE user_shows 
ADD num_comments INT(4);

UPDATE user_shows SET num_comments = (SELECT count(id) FROM comments WHERE comments.id = user_shows.id);

答案 1 :(得分:1)

我建议您为此目的创建view

如下所示:

create view user_shows_comments  as (

   SELECT u.*,count(c.id) as num_comments
   FROM user_shows  as u left join comments as c on u.id=c.user_id
   group  by c.user_id
) 

使用此视图进行进一步查询。它将自动使用表格进行更新。