1

To begin with I have two tables:

feeds:(id,content_id,author) and feeds_ratings:(id,feed_id (FK to feeds(id)),user_id,rating)

What I want to do is get the total rating difference for a specific author by a certain user.

To explain a bit more, let's say we have three rows in the feeds table, (1,3245,test),(2,3215,test),(3,3122,test) and tree rows on the feeds_ratings table, (1,1,12,like), (1,2,12,like),(1,3,12,dislike)

The input will be the user_id and the author and I want the output to be the difference between the total dislikes and likes by the input user, for the specific input author. (In this example it will be 1 because of the two likes and the one dislike.

How can that be implemented in a mysql query? I tried searching and some code of my own but I can't make it work, so any help is appreciated!

1
  • Why not provide a sqlfiddle? (This should be a standard requirement.) Commented May 27, 2013 at 15:22

1 Answer 1

2

Something like this will work using SUM with CASE -- add 1 for likes and -1 for dislikes:

SELECT SUM(CASE WHEN fr.rating = 'like' THEN 1 ELSE -1 END) TotalLikes
FROM Feeds F
  INNER JOIN Feeds_Ratings FR ON F.id = FR.feed_id
WHERE F.author = 'test' 
  AND FR.user_id = 12

Obviously replace author and user_id with the appropriate values -- these are just for your sample input.

Sign up to request clarification or add additional context in comments.

2 Comments

Sweet lord that was fast! I couldn't figure out how to do the sum part, thanks a lot. I will mark it as accepted in a jiffy.
@Systemfreak -- np, glad I could help!

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.