2

Basically I have a table with comments:

id     target_item_id        comments
--------------------------------------
1      435                   blah blah
2      643                   blah blah
3      643                   blah blah
4      643                   blah blah

And a different, relational table with like and dislike votes for each comment:

id      comment_id          like
----------------------------------
1       2                   1
2       2                   1
3       2                   0
4       3                   1
5       3                   0
6       4                   1

comment_id on the second table relates to id on the first table. Basically I need a query that will select, for example, all comments for a specific target_item from the first table, but order the comments by popularity score. Popularity score is calculated by counting all likes (1s) and dislikes(0s) for a specific comment on the second table and subtracting the second result from the first. In this example, comment id 2 would have a popularity score of 1: count of likes (1s) is 2 and count of dislikes (0s) is 1: 2 - 1 = 1.

Would I be able, via MySQL, to create a query that will select the comments and order them by the popularity score in the fashion described above? Or would I have query each comment individually to acquire the score?

Hope it's clear enough to understand. Thanks in advance.

2 Answers 2

2
select c.id, c.target_item_id, c.comments,
       sum(case when v.`like`=1 then 1 when v.`like`=0 then -1 end) popularity
from comments c
left join votes v on v.comment_id = c.id
where c.target_item_id = 643
group by c.id, c.target_item_id, c.comments
order by popularity desc
1
  • Tried that but it is getting the SUM of all votes for the particular target_item instead of the SUM for each specific comment. Any ideas?
    – jacob
    Mar 28, 2011 at 20:56
0

It would be easier if you changed the dislike value from 0 to -1. Then you could just Sum() the like column.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.