mysqli - Double INNER JOIN and SUM -
table pckeyword kwid | keyword
table prophrase kwid | vote
table contraphrase kwid | vote
so vote column integer , want sum specified keyword this:
examplekeyword | 12 | 47
til have doesnt work correctly:
select pckeyword.kwid, pckeyword.keyword, sum( prophrase.vote ) provotes, sum( contraphrase.vote ) contravotes pckeyword inner join prophrase on prophrase.kwid = pckeyword.kwid inner join contraphrase on contraphrase.kwid = prophrase.kwid group pckeyword.keyword order pckeyword.keyword asc
you try:
select kwid, keyword, provotes, contravotes pckeyword inner join ( select kwid pid, sum( vote ) provotes prophrase group kwid ) p on pid = kwid inner join ( select kwid cid, sum( vote ) contravotes contraphrase group kwid ) c on cid = kwid
this way grouping once in derived tables , not often! (by separating tables derived tables tidy whole syntax, since column names unique within each derived table expression.)
see here: http://sqlfiddle.com/#!2/70634/1
edit
just completeness, here version left join
s , coalesce()
make sure meaningful results cases there no votes:
select kwid, keyword, coalesce(provotes,0) provotes, coalesce(contravotes,0) contravotes pckeyword left join ( select kwid pid, sum( vote ) provotes prophrase group kwid ) p on pid = kwid left join ( select kwid cid, sum( vote ) contravotes contraphrase group kwid ) c on cid = kwid
sqlfiddle: http://sqlfiddle.com/#!2/ec51cb/1
Comments
Post a Comment