mysql根据辅助表中的行重新计数mysql中的列

发布于 2024-08-21 11:36:17 字数 674 浏览 5 评论 0原文

我接管了一个包含两个表的数据库,将它们命名为 entriescommentsentries 表包含一个名为 comment_count 的列,该列保存 comments 中具有与 entries 中该行相对应的entry_id 的行数。

最近,由于代码库的版本切换,这种连接变得非常不同步。我需要帮助来构建一个在 phpmyadmin 中运行的查询,以再次同步这些数字。 entries 中的行数约为 8000,comments 中的行数约为 80000,因此运行同步查询应该不会有任何问题。

结构:

  • entries countains:
  • id | comment_count |等
  • comments 包含
  • id | blogentry_id | 我能想到的

唯一方法是使用 php 循环 entries 表中的每个条目并单独更新,但这与纯 SQL 解决方案相比似乎极其脆弱。

我会感谢任何帮助!

I took over a database with two tables, lets name them entries and comments.
The entries table contains a column named comment_count which holds the amount of rows with entry_id in comments corresponding to that row in entries.

Lately this connection has become terribly out of sync due to version switching of the codebase. I need help to build a query to run in phpmyadmin to sync these numbers again. The amount of rows in entries is around 8000 and the rows in comments is around 80000 so it shouldn't be any problems to run the sync-query.

Structure:

  • entries countains:
  • id | comment_count | etc
  • comments contains
  • id | blogentry_id | etc

The only way I can think of is to loop each entry in the entries table with php and update individually but that seems extremly fragile compared to a pure SQL solution.

I'd appriciate for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2024-08-28 11:36:17
INSERT
INTO    entries (id, comment_count)
SELECT  blogentry_id, COUNT(*) AS cnt
FROM    comments
GROUP BY
        blogentry_id
ON DUPLICATE KEY
UPDATE  comment_count = cnt
INSERT
INTO    entries (id, comment_count)
SELECT  blogentry_id, COUNT(*) AS cnt
FROM    comments
GROUP BY
        blogentry_id
ON DUPLICATE KEY
UPDATE  comment_count = cnt
一影成城 2024-08-28 11:36:17

我认为纯 SQL 解决方案将涉及使用子查询从以条目表作为驱动程序的注释表中收集计数。类似下面的内容应该在条目表上“循环”,并为每一行执行子查询(这可能是不正确的术语)并将注释计数更新为辅助表的相应计数。希望有帮助!

UPDATE   entries ent
   SET   comment_count =
         (SELECT   COUNT ( * )
            FROM   comments cmt
           WHERE   cmt.blogentry_id = ent.id)

I think a pure SQL solution would invlolve using a subquery to gather the counts from the comments table having the entries table as the driver. Something like the following should "loop" over the entries table and for each row perform the subquery (that may be the incorrect terminology) and update the comment count to be that of the corresponding counts off of the auxillary table. Hope that helps!

UPDATE   entries ent
   SET   comment_count =
         (SELECT   COUNT ( * )
            FROM   comments cmt
           WHERE   cmt.blogentry_id = ent.id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文