【问题标题】:Incrementing a mysql field when i add data to another field当我将数据添加到另一个字段时增加一个 mysql 字段
【发布时间】:2016-07-27 07:19:57
【问题描述】:

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

我创建了两个 mysql 表(articles 和 cmets)。 article存储不同的文章,cmets存储与一篇文章相关的所有cmets。

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

文章有唯一的 ID,称为 article_id

当有人评论一篇文章时,评论被插入到评论表中,comment_id被更新,article_id也被存储。

如果有人回复了文章本身,则在评论表条目上将 parent_id 设置为 0,并将该 article_id 的文章表中的 number_of_replies 加 1。

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

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

  1. 将新评论添加到评论表中(更新所有字段)
  2. 将文章表中该文章的 number_of_replies 加 1
  3. 如果回复已有评论,则在cmets表中parent_id对应的评论中加1

是否可以同时进行所有三个操作?如果是这样,那么执行此操作的 mysql 语句是什么。如果不是,分别执行的语句是什么?

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

谢谢

【问题讨论】:

  • 您可以将它们全部组合到一个存储过程中,这样它们就可以在一个命令中轻松执行,并将语句包装在事务中,这样如果一个失败,它们都可以(所以你不得到不一致的数据)。或者您可以将触发器视为另一种选择。

标签: mysql


【解决方案1】:

您应该在需要这些数字时简单地查询数据库,而不是将 cmets/回复的数量存储在表中,如下所示:

SELECT COUNT(*) FROM comment_table WHERE article_id = ?

SELECT COUNT(*) FROM comment_table WHERE parent_id = ?

像你一样存储它们的唯一原因是作为一种优化,但我认为这充其量只是一个增量速度改进,即使在大型网站上也是如此。

否则,你应该像ADyson所说的那样,使用程序和事务。

【讨论】:

    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多