SQL-为每个用户选择文章总数和文章评论总数

时间:2019-03-02 20:20:17

标签: mysql sql database

我正在尝试为每个用户获取文章总数,为每个文章获取评论总数,就像这样:

username | total_articles | total_comments
John Doe |      3         |    10

这是我的SQL,直到现在,我正在使用MySQL:

SELECT u.id, u.username, COUNT(a.id) AS total_articles, COUNT(c.id) AS total_comments FROM users u
LEFT JOIN articles a ON u.id = a.user_id
LEFT JOIN comments c ON a.id = c.article_id
GROUP BY u.id;

我试图同时按u.ida.idc.id分组,但是无法正常工作。

谢谢。

5 个答案:

答案 0 :(得分:0)

在分组依据中同时使用u.id, u.username两列

SELECT u.id, u.username, COUNT(a.id) AS total_articles,
 COUNT(c.id) AS total_comments FROM users u
LEFT JOIN articles a ON u.id = a.user_id
LEFT JOIN comments c ON a.id = c.article_id
GROUP BY u.id, u.username

答案 1 :(得分:0)

您在u.username中缺少group by,而且COUNT(a.id)也必须更改为COUNT(distinct a.id)

SELECT u.id, u.username, COUNT(distinct a.id) AS total_articles, COUNT(c.id) AS total_comments FROM users u
LEFT JOIN articles a ON u.id = a.user_id
LEFT JOIN comments c ON a.id = c.article_id
GROUP BY u.id, u.username;

更新:

但是,我想您实际需要的不是建议的查询。您说您需要每个用户的文章总数每个文章的评论总数。这意味着您需要两个单独的查询:

SELECT a.id article_id , COUNT(c.id) AS total_comments
FROM articles a 
LEFT JOIN comments c ON a.id = c.article_id
GROUP BY a.id

SELECT u.id, u.username, COUNT(distinct a.id) AS total_articles
FROM users u
LEFT JOIN articles a ON u.id = a.user_id
GROUP BY u.id, u.username;

答案 2 :(得分:0)

您正在沿相关维度进行汇总,并开始计算过多。

一种方法是使用多个聚合:

SELECT u.id, u.username, COUNT(a.id) AS total_articles,
       SUM(c.num_comments) AS total_comments
FROM users u LEFT JOIN
     articles a
     ON a.user_id = a.id LEFT JOIN
     (SELECT c.article_id, COUNT(c.id) as num_comments
      FROM comments c
      GROUP BY c.article_id
     ) c
     ON a.id = c.article_id
GROUP BY u.id, u.username;

答案 3 :(得分:0)

如果您想要的是用户的文章数,以及该用户所有文章的评论总数-那么这是您的查询:

SELECT
    u.id,
    u.username,
    COUNT(DISTINCT a.id) AS total_articles,
    COUNT(c.id) AS total_comments
FROM users u
LEFT JOIN articles a 
    ON u.id = a.user_id
LEFT JOIN comments c 
    ON a.id = c.article_id
GROUP BY
    u.id,
    u.username;

但是-如果您要查找用户的评论数(此处只是一个想法)-那么您想在用户ID而非文章ID上加入评论表。

答案 4 :(得分:0)

在第一个查询中,所有用户的文章,在第二个查询中,所有用户加入的评论

  

编辑:使用LEFT JOIN插入的JOIN

SELECT id_total_articles, username, total_articles, total_comments 
              FROM 
                  (
                    SELECT u.id as id_total_articles, u.username, COUNT(a.id) AS total_articles FROM users u
                    LEFT JOIN articles a ON u.id = a.user_id
                    GROUP BY u.id, u.username
                ) as  AC 
                 left join 
                (
                  SELECT u.id as id_total_comments, COUNT(c.id) AS total_comments FROM users u
                  LEFT JOIN comments c ON u.id = c.user_id
                  GROUP BY u.id, u.username 
                ) as  CC 
            ON AC.id_total_articles = CC.id_total_comments;