代码之家  ›  专栏  ›  技术社区  ›  Renuka sharma

MySql查询,用于统计两个表中引用id为第三个表的行总数

  •  -2
  • Renuka sharma  · 技术社区  · 1 年前

    假设我有三张桌子-

    blogs,
    comments,
    replies
    

    在the blogs 表中,我有一列名为 blog_id ,此id也是 博客 桌子。

    在the comments 桌子,我有 comment_id 作为主键,以及 comm_blog_id 作为外键 blog_id .

    在the replies 桌子,我有 reply_id 作为主键, reply_blog_id 作为外键 blog_id ,以及 reply_comm_id 作为外键 comment_id .

    像这样-

    blog1
       comment1
          reply1
    
    blog2
       comment1
          reply1
    
    blog3
       comment1
       comment2
          reply1
       comment3
    
    blog4
       comment1
          reply1
          reply2
          reply3
       comment2
       comment3
    

    现在,如果我想计算总数 count 属于 comments and replies 结合在 blog1 必须是 2 在里面 blog2 必须是 2. 在里面 blog3 成为 4 和in blog4 必须如此 6 .

    我写的问题如下:

    SELECT
        blogs.blog_id = '1',
        (
            (SELECT COUNT(*) FROM comments WHERE comments.comm_blog_id = blogs.blog_id) +
            (SELECT COUNT(*) FROM replies WHERE replies.reply_blog_id = blogs.blog_id)
        ) AS total_count
    FROM blogs;
    

    这给了我正确的结果,但也给了我行数,我不知道为什么会发生这种情况。

    我研究了很多,但我没有找到正确的地方,有人能告诉我我哪里错了吗,或者还有其他查询可以计算特定博客中的所有行。

    我知道php注释 mysqli_num_rows($result) 统计行数,但只有当我们有行数的数据时才会发生这种情况。

    我想计算总数 计数 属于 评论和回复 结合在 博客1

    blogs_table

    comments_table

    replies_table

    1 回复  |  直到 1 年前
        1
  •  -1
  •   Akshay03    1 年前

    试试这个

    SELECT blog_id, COUNT(*) AS total_references
        FROM (
            SELECT comm_blog_id AS blog_id
            FROM comments
            UNION ALL
            SELECT reply_blog_id AS blog_id
            FROM replies
        ) AS combined_references
        GROUP BY blog_id;