2016-08-16 80 views
0

我正在實現一個帶有MySQL和Node.js的投票系統,它現在工作良好,但有1個問題。我有一個表文章與2關係upvotesdownvotesMySQL選擇2個關係的計數

如果我去找我的所有文章,我想有upvotesdownvotes計數。第一個表是用

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嗎?

謝謝!

馬茨

+1

同樣的方式你做了downvotes – VikingBlooded

+0

2連接對於Mysql來說是相當簡單的任務。做到這一點。 – Serg

回答

1

添加另一個左連接的upvotes

您添加的downvotes
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 
+0

請看下面,我正在尋找。 http://stackoverflow.com/a/38981844/1518174 – Matz

2

同樣的方式。另外,確保你習慣於格式化你的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 
+0

就是這樣。非常感謝,格式良好是一個很好的觀點。 – Matz

+0

沒有語法錯誤:/我得到了相同數量的downvotes/upvotes,但我只有1 downvote和2 upvotes。 – Matz

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

他告訴我問題出在結束該組。第一個左連接的結果將被第二個左連接覆蓋。