MySQL选择2个关系的计数

时间:2016-08-16 18:11:44

标签: mysql sql

我正在实施一个使用MySQL和Node.js的投票系统,它目前运作良好,但有一个问题。我有一个表文章,其中包含两个关系 upvotes downvotes

如果我抓取所有文章,我想计算 upvotes downvotes 。第一个表正在使用

SELECT articles.*, count(downvotes.articles_id) 
as downvotes 
from articles 
left join downvotes 
on (articles.id = downvotes.articles_id) 
where articles.communities_id = '52' 
group by articles.id 
ORDER BY created_at 
DESC [![Sequel Pro][1]][1]

如何在查询中添加 upvotes

谢谢!

Matz的

3 个答案:

答案 0 :(得分:2)

你添加了downvotes的方式相同。此外,请确保您养成了格式化SQL的习惯,使其更易于阅读和调试。

SELECT 
    articles.*,
    COUNT(downvotes.articles_id) AS downvotes,
    COUNT(upvotes.articles_id) AS upvotes
FROM
    articles
        LEFT JOIN
    downvotes ON (articles.id = downvotes.articles_id)
        LEFT JOIN
    upvotes ON (articles.id = upvotes.articles_id)
WHERE
    articles.communities_id = '52'
GROUP BY articles.id
ORDER BY created_at DESC

答案 1 :(得分:1)

为upvotes添加另一个左连接

SELECT articles.*, count(downvotes.articles_id) as downvotes 
from articles 
left join downvotes on (articles.id = downvotes.articles_id) 
left join upvotes on (articles.id = upvotes.articles_id) 
where articles.communities_id = '52' 
group by articles.id 
ORDER BY created_at DESC

答案 2 :(得分:0)

好的,朋友发布了正确答案:

SELECT a.id, (SELECT COUNT(*) FROM downvotes d WHERE a.id=d.articles_id) AS `downs`, (SELECT COUNT(*) FROM upvotes u WHERE a.id=u.articles_id) AS `ups` FROM articles a ORDER BY a.id ASC

他告诉我问题是最后的小组。第一个左连接的结果将被第二个左连接覆盖。