I have a table called comments with the columns: posID
and commentLikes
.
tableComments
| postID | commentLikes |
+-----------+--------------+
| 233 | 2 |
| 233 | 0 |
| 675 | 2 |
| 345 | 12 |
| 345 | 8 |
In my PHP code, I am passing the PostID variable to my function.
I want to get the number of likes for each post based on postID passed into the function so I will need the WHERE clause.
I have tried using COUNT and GROUP BY but still no luck. So I need to count each time the postID matches a value and then add up the total number of likes. How can I do this?
If you're passing a single postID
you don't need a group by
clause, you just need to use it in the where
clause and sum
the likes:
SELECT SUM(likes)
FROM tableComments
WHERE postId = ?
The "?" should of course be bound from the PHP code.
You don't need a GROUP BY
since you will filter the records passed on the POstId
you are passing.Just do a summation on the records you will get the desired results.
SELECT SUM(commentLikes)
FROM comments
WHERE postID=@PostID
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.