简体   繁体   English

如何从每个列出现的SQL中获取值?

[英]How can I get a value from SQL where each column occurs?

I have a table called comments with the columns: posID and commentLikes . 我有一个名为comments的表,其中包含列: posIDcommentLikes

   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. 在我的PHP代码中,我将PostID变量传递给我的函数。
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. 我希望根据传递给函数的postID获取每个帖子的喜欢数量,因此我需要WHERE子句。

I have tried using COUNT and GROUP BY but still no luck. 我尝试过使用COUNTGROUP BY,但仍然没有运气。 So I need to count each time the postID matches a value and then add up the total number of likes. 所以我需要在每次postID匹配一个值时计算,然后加上喜欢的总数。 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: 如果你传递一个postID你不需要group by子句,你只需要在where子句中使用它并sum喜欢:

SELECT SUM(likes)
FROM   tableComments
WHERE  postId = ?

The "?" “?” should of course be bound from the PHP code. 当然应该从PHP代码绑定。

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. 您不需要GROUP BY因为您将过滤在您传递的POstId上传递的记录。 POstId对记录求和,您将获得所需的结果。

SELECT SUM(commentLikes)
FROM comments 
WHERE postID=@PostID 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM