双INNER JOIN和SUM

时间:2013-08-26 15:05:19

标签: mysqli sum inner-join

表pcKeyword kwId |关键字

表格proPhrase kwId |表决

表格ContraPhrase kwId |表决

因此,投票列是一个整数,我想为指定的关键字求和 像这样:

exampleKeyword | 12 | 47

现在我有了这个,但我没有正常工作:

    SELECT pcKeyword.kwId, pcKeyword.keyword, SUM( proPhrase.vote ) AS proVotes, SUM( contraPhrase.vote ) AS contraVotes
FROM pcKeyword
INNER JOIN proPhrase ON proPhrase.kwId = pcKeyword.kwId
INNER JOIN contraPhrase ON contraPhrase.kwId = proPhrase.kwId
GROUP BY pcKeyword.keyword ORDER BY pcKeyword.keyword ASC

1 个答案:

答案 0 :(得分:0)

你可以尝试:

SELECT kwId, keyword, proVotes, contraVotes
FROM pcKeyword
INNER JOIN ( SELECT kwId pid, SUM( vote ) proVotes  
             FROM proPhrase GROUP BY kwId )  p ON pid = kwId
INNER JOIN ( SELECT kwId cid, SUM( vote ) contraVotes
             FROM contraPhrase GROUP BY kwId ) c ON cid = kwId

这样,您只能在派生表中进行一次分组,而不是经常进行分组! (通过将表分成它们的派生表,我也可以整理整个语法,因为现在列名在每个派生表表达式中都是唯一的。)

见这里:http://sqlfiddle.com/#!2/70634/1

修改

为了完整起见,此处包含LEFT JOINCOALESCE()的版本,以确保您在没有投票的情况下获得有意义的结果:

SELECT kwId, keyword, 
       COALESCE(proVotes,0) proVotes, 
       COALESCE(contraVotes,0) contraVotes
FROM pcKeyword
LEFT JOIN ( SELECT kwId pid, SUM( vote ) proVotes  
             FROM proPhrase GROUP BY kwId )  p ON pid = kwId
LEFT JOIN ( SELECT kwId cid, SUM( vote ) contraVotes
             FROM contraPhrase GROUP BY kwId ) c ON cid = kwId

SQLfiddle:http://sqlfiddle.com/#!2/ec51cb/1