mankee mankee - 2 months ago 7
MySQL Question

Joining two Queries in SQL

I'm trying to get the total sum of likes a user has on his posts in SQL. Essentially I have the following table design:

Table Content :


  1. content_id

  2. poster_id



Table Likes :


  1. content_id

  2. upvoteOrDownVote

  3. liker_id



So essentially what I need to do is get all of the
content_id
from the
Content
table, where
poster_id == user
and then for each of those
content_id
I need to get all likes from the
Likes
table. It's easy to do these queries separately, but I'm not sure how to combine it into one query.

Answer

Simply join the two tables and use COUNT(*) to count the selected rows.

SELECT COUNT(*) AS likes
FROM Likes AS l
JOIN Content AS c ON l.content_id = c.content_id
WHERE c.poster_id = user
AND l.upvoteOrDownVote = 'upvote'
Comments