sql - MySQL sum negative and sum of positive values without sub query -
sql - MySQL sum negative and sum of positive values without sub query -
i have 2 tables follows:
tbl_answers : id, (fk)authorid ... tbl_answer_votes : id, (fk)voterid, (fk)answerid, vote (sint, ever -1 or 1)
tbl_answers
has 1 many relationship tbl_answer_votes
, vote can either negative 1 or positive 1.
i need bring together tbl_answer_votes
on tbl_answers
produce sum of negative votes reply , sum of positive votes reply 2 separate columns.
i can sub-querying little part of larger query , after reading pitfalls on sub-queries seek , produce 2 negative , positive sums votes table efficiently possible.
you can utilize case
, join
accomplish this:
select a.id, sum(case v.vote when 1 1 else 0 end) upvotes, sum(case v.vote when -1 1 else 0 end) downvotes tbl_answers inner bring together tbl_answer_votes v on v.id = a.id grouping a.id
this returns id
tbl_answers
, 2 columns total votes of either value tbl_answer_votes
. didn't specify (if any) other columns you'd want either table, may have adjust column list in select
, group by
portions add together additional columns.
mysql sql
Comments
Post a Comment