MySQL select with a count query on another table

馋奶兔 提交于 2019-12-06 07:28:34
SELECT a.title AS title, u.username AS username, count(c.id) as total_comments FROM articles a
   LEFT JOIN comments c ON c.article_id = a.id
   LEFT JOIN users u ON a.user_id = u.id
GROUP BY a.id

How about something like this, can't test it right now so it might have errors.

SELECT a.title, u.username, COUNT(*) total_comments
FROM article a
  JOIN user u ON (u.id=a.user_id)
  LEFT OUTER JOIN comment c ON (c.article_id=a.id)
GROUP BY a.title, u.username
SELECT article.title AS title, COUNT(  'comment.id' ) AS total_comment, user.username AS username
FROM article
JOIN COMMENT ON comment.article_id = article.id
JOIN user ON user.id = article.user_id
GROUP BY article.id

If you try this that it answer?

SELECT a.title AS title, 
             u.username AS username, 
             count(c.id) AS total_comments 
 FROM articles a, comments c, users u
 WHERE  a.user_id =u.id
    And a.id=c.articles_id
    And c.user_id = u.id 

Or with inner syntax

SELECT a.title AS title, 
             u.username AS username, 
             count(c.id) AS total_comments 
 FROM articles a 
 INNER JOIN comments c ON c.article_id = a.id 
                                          AND c.user_id=u.id
 INNER JOIN users u ON a.user_id = u.id 
 GROUP BY a.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!