php 来自相同 ID 的 SQL 列的 SUM 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16260710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SUM values from SQL column from same ID
提问by markb
This is the comment_meta from wordpress. In there is a custom meta_key: rating.
这是来自 wordpress 的 comment_meta。其中有一个自定义的 meta_key: rating。
I would like to get the SUM of all the ratings for that individual post.
我想获得该个人帖子的所有评分的总和。
The point being of this is to get the average from the user ratings. I have the total number of commenters, I just need the SUM.
关键是要从用户评分中获得平均值。我有评论者的总数,我只需要 SUM。
The use of it is for the Schema.org AggregateReview: <meta itemprop="ratingValue" content=""/>
.
它用于 Schema.org AggregateReview: <meta itemprop="ratingValue" content=""/>
。
I have tried to add the value via jQuery, but for some reason the schema isn't registering the text added later in the DOM.
我尝试通过 jQuery 添加值,但由于某种原因,架构没有注册稍后在 DOM 中添加的文本。
var sum = 0;
$('.comment_rate').each(function(){
numItems = $('.comment_rate').length
sum += (parseFloat($(this).text()) / numItems);
$('span[itemprop="ratingValue"]').text(sum);
});
ORIGINAL POST
原帖
I have this table (sorry, image is only way I know how to show):
我有这张表(抱歉,图像只是我知道如何显示的方式):
I would like to sum the meta_value
from the matching comment_id
.
我想meta_value
从匹配的comment_id
.
So far I have this but it SUMs the entire column not the ones matching the same id.
到目前为止,我有这个,但它对整个列进行求和,而不是与相同 ID 匹配的列。
<?php
$result = mysql_query('SELECT SUM(meta_value) AS value_sum FROM wp_play_commentmeta');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
?>
回答by Mahmoud Gamal
Use a GROUP BY
:
使用GROUP BY
:
SELECT comment_id, SUM(meta_value) AS value_sum
FROM wp_play_commentmeta
GROUP BY comment_id;
See it in action here:
在这里查看它的实际效果:
If you want to do this for only those that had rating
metakey, then add that in the WHERE
clause. Something like this:
如果您只想对那些具有元rating
密钥的人执行此操作,请将其添加到WHERE
子句中。像这样的东西:
SELECT comment_id, SUM(meta_value) AS value_sum
FROM wp_play_commentmeta
wHERE meta_key = 'rating'
GROUP BY comment_id;
Update:
更新:
JOIN
the two tables, and GROUP BY post_id
. Something like this:
JOIN
两个表,和GROUP BY post_id
。像这样的东西:
SELECT
p.post_id,
SUM(m.meta_value) AS value_sum
FROM wp_play_commentmeta AS m
INNER JOIN wp_play_comments AS p ON m.comment_ID = p.comment_Id
wHERE meta_key = 'rating'
GROUP BY p.post_id;
Note that:Please stop using Mysql_*
extensions, they are deprecated. Furtheremore your code this way is vulnerable to SQL Injection. Use PDO
or prepared statements instead.
请注意:请停止使用Mysql_*
扩展,它们已被弃用。此外,您的代码以这种方式容易受到SQL Injection 的攻击。改用PDO
或准备好的语句。
回答by Shafqat Masood
query will be
查询将是
SELECT SUM(meta_value) AS value_sum, comment_id FROM wp_play_commentmeta
Group by comment_id