3

I have tried to fetch records from 2 tables but it is not showing required output where my first table is ttreply

ttreply table

And another table is ttreplycount where count stored as below:

ttreplycount

I have tried to fetch value but it doesn't fetch records as i want my mysql query as below:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes,0) as Votes 
FROM `ttreply` r left join 
(SELECT sum(votes) as Votes from `ttreplyvotes` )x ON r.`post_id`=2 

Which showing me output like this:

Output

What i needed is like this:

id  userid    reply                Votes
2   3       Testing 2nd reply      -2
3   3       Testing 3nd reply       0
4   3        rewsf                  0

Any help would be helpful.

1
  • How do you determine which row gets the votes value? Commented Sep 22, 2015 at 12:07

1 Answer 1

2

You can get the rows you want by moving the condition to the where clause:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes,0) as Votes 
FROM `ttreply` r cross join 
     (SELECT sum(votes) as Votes from `ttreplyvotes` ) x 
WHERE r.`post_id` = 2 ;

This will have -2 for all three rows. Why do you want the total on only one row? How do you determine which row gets the total?

EDIT:

Oh, I think I understand:

SELECT r.id, r.userid, r.`reply`, coalesce(x.votes, 0) as Votes 
FROM `ttreply` r left join 
     (SELECT replyid, sum(votes) as Votes
      FROM `ttreplyvotes`
      GROUP BY replyid
     ) x 
     ON x.replyid = r.id
WHERE r.`post_id` = 2 ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.