CrazyMax
CrazyMax

Reputation: 801

Group sql query

I want to have an only query with 2 queries but i don't know how to start... My queries count the positive/negative votes for a comment.

SELECT COUNT(id) AS votes_no FROM comments_votes WHERE vote = 0 AND id_comment = 1
SELECT COUNT(id) AS votes_no FROM comments_votes WHERE vote = 1 AND id_comment = 1

I set vars to put negative and positives votes : $votes_no and $votes_yes

Then i have a final var : $votes_calc = $votes_yes - $votes_no;

How can i get the number of votes_yes, votes_no and votes_calc in only one query?

Thanks a lot!

Upvotes: 1

Views: 104

Answers (3)

CrazyMax
CrazyMax

Reputation: 801

I merge the query getting the comments and the comments votes and it seems to work :)

SELECT a.*, nb_votes, votes_yes-votes_no AS votes_calc
FROM comments AS a
LEFT JOIN (
    SELECT id_comment, COUNT(id) AS nb_votes,
    SUM(CASE WHEN vote = 0 THEN 1 ELSE 0 END) AS votes_no,
    SUM(CASE WHEN vote = 1 THEN 1 ELSE 0 END) AS votes_yes
    FROM comments_votes GROUP BY id_comment
) AS c ON (a.id = c.id_comment)
WHERE a.status = 'approved' AND a.id_post = 1 ORDER BY a.time ASC

Thanks for your answers :)

Upvotes: 0

Joe Stefanelli
Joe Stefanelli

Reputation: 135808

select votes_no, votes_yes, votes_yes-votes_no as votes_calc
from (select sum(case when vote = 0 then 1 else 0 end) as votes_no,
             sum(case when vote = 1 then 1 else 0 end) as votes_yes
      from comments_votes
      where id_comment = 1) a

Upvotes: 2

Sparky
Sparky

Reputation: 15075

select vote,count(id)
from Comment_votes
group by vote
WHERE id_comment = 1
with rollup

The with Rollup will add a row with a NULL value in the vote column and the total in the second column

Upvotes: 2

Related Questions