【问题标题】:Schedule and update with count of a different table使用不同表的计数计划和更新
【发布时间】:2019-08-13 04:39:05
【问题描述】:

我有 3 张这样的桌子

questions_table

question_id | content           |  user             |
1           | my first question | userOne@email.com |
2           | my second question | userTwo@email.com|

replies_table

reply_id | question_id|user                |content               |voteCount|
1        |      1     |userSeven@email.com |first reply question 1 |0       |
2        |      1     |userEight@email.com |second reply question1 |0       |

投票表

vote_id  | reply_id|  voted_by          |
1        |      2  | userThree@email.com|
2        |      2  | userFour@email.com |

所以解释一下:

  1. 两个用户userOne@email.comUserTwo@email.com
  2. 然后userSeven@email.comuserEight@email.com回复 问题 1。
  3. 然后userEight@email.com 的回复有reply_id2 被投票赞成 userThree@email.comuserFour@email.com

我需要做的是在 myphpmyadmin 中编写一个每 2 小时运行一次的事件调度程序。 我想要查询做的是通过计算对该回复ID的投票来更新replies_table中的voteCount列。 这就是我到目前为止所得到的

SELECT COUNT(voteCount)
FROM replies_table
WHERE reply_id = .../**dont know how am i suppose to do this part **/;

我知道会是这样,但我从未编写过事件调度程序

【问题讨论】:

    标签: mysql sql phpmyadmin mysql-event


    【解决方案1】:

    您可以简单地使用join 来获取总票数。

      select r.reply_id, v.Countreply as count from replies_table as r 
      inner join 
      (select reply_id, count(reply_id) as CountReply from vote_table group by reply_id) as v 
      on r.reply_id= v.reply_id
    

    如果你想更新那么它只是通过更新来完成。

     update r set r.votecount = v.Countreply 
      from replies_table as r inner join 
      (select reply_id, count(reply_id) as CountReply from vote_table group by reply_id) as v 
      on r.reply_id= v.reply_id
    

    【讨论】:

      【解决方案2】:

      在 MySQL 中,您可以将 update 表示为:

      我希望查询做的是通过计算对该回复 id 的投票来更新 replies_table 中的 voteCount 列。这就是我到目前为止所得到的

      update replies_table rt join
             (select reply_id, count(*) as numvotes
              from votes v
              group by reply_id
            ) v
          set rt.VoteCount = v.numvotes;
      

      这可能不是让您的数据保持最新的最佳方式。

      如果您的表不是很大,则无需单独存储VoteCount。只需在需要时运行查询即可。

      如果VoteCount 确实很重要,请使用触发器使其保持最新状态。

      而且,即使您采用这条路线,也无需更新所有行。您可以跟踪时间戳和上次更新时间以限制更新次数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-11
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-18
        • 2016-03-20
        相关资源
        最近更新 更多