简体   繁体   中英

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!

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

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

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM