当我将数据添加到另一个字段时,增加一个mysql字段

时间:2016-07-26 21:26:17

标签: mysql

我是mysql的新手。我正在创建一个评论系统作为一个mysql练习,用户可以在其中评论不同的文章,并回复其他用户对该文章的评论,如树。

我创建了两个mysql表(文章和评论)。这些文章存储了不同的文章,评论存储了与文章相关的所有评论。

The article table:
    article_id        - unique auto increment integer (primary key)
    text              - text of the article
    number_of_replies - total number of people who commented on this article

The comment table:
    comment_id        - unique auto increment integer (primary key)
    article_id        - article being replied to
    parent_id         - the comment_id this comment is replying to, zero if root
    number_of_replies - number of people who replied to this comment
    comment           - the text of the comment

文章具有名为article_id的唯一ID

当有人对文章发表评论时,评论会被插入到评论表中,并且comment_id会更新,而且article_id也会被存储。

如果有人回复了文章本身,那么在注释表条目上将parent_id设置为0,并且还为该article_id的文章表中的number_of_replies添加1。

当有人回复comment_id 1时,会将一个新的comment_id 2插入到其parent_id设置为1的表中,同时将1添加到comment_id 1的number_of_replies列,并且还将number_of_replies添加1该article_id的文章表。

所以当我添加评论时,我必须做三个mysql操作

  1. 将新评论添加到评论表(更新所有字段)
  2. 在文章表
  3. 中为该文章的number_of_replies添加1
  4. 如果回复现有评论,请在评论表中与parent_id对应的评论中添加1
  5. 是否可以同时进行所有三项操作?如果是这样,那么mysql语句是做什么的。如果没有,那么单独进行这些陈述的是什么?

    我是mysql的新手,所以如果有什么不清楚,或者我问愚蠢的问题,请告诉我。

    由于

1 个答案:

答案 0 :(得分:0)

您应该只在需要这些数字时查询数据库,而不是在表格中存储评论/回复的数量,如下所示:

SELECT COUNT(*) FROM comment_table WHERE article_id = ?

SELECT COUNT(*) FROM comment_table WHERE parent_id = ?

像你这样存储它们的唯一理由是优化,但我认为即使在大型网站上,这也是最佳的增量速度提升。

否则,你应该像ADyson那样说并使用程序和交易。

相关问题