来自同一ID的SQL列的SUM值

mar*_*rkb 6 php mysql sql jquery schema.org

这是来自wordpress的comment_meta.在有一个自定义meta_key:评级.

我想获得该帖子所有评级的总和.

这样做的目的是从用户评级中获得平均值.我有评论者的总数,我只需要SUM.

它的使用是针对Schema.org AggregateReview的:<meta itemprop="ratingValue" content=""/>.

我试图通过jQuery添加值,但由于某种原因,架构没有注册稍后在DOM中添加的文本.

var sum = 0;
$('.comment_rate').each(function(){
    numItems = $('.comment_rate').length
    sum += (parseFloat($(this).text()) / numItems);
    $('span[itemprop="ratingValue"]').text(sum);
});
Run Code Online (Sandbox Code Playgroud)

原始邮政

我有这张桌子(对不起,图片只是我知道如何展示的方式): 在此输入图像描述

我想meta_value从匹配中总结一下comment_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;
?>
Run Code Online (Sandbox Code Playgroud)

Mah*_*mal 11

使用GROUP BY:

SELECT comment_id, SUM(meta_value) AS value_sum 
FROM wp_play_commentmeta
GROUP BY comment_id;
Run Code Online (Sandbox Code Playgroud)

在这里看到它:


如果您只想为那些拥有ratingmetakey的人执行此操作,请在WHERE子句中添加该元素.像这样的东西:

SELECT comment_id, SUM(meta_value) AS value_sum 
FROM wp_play_commentmeta
wHERE meta_key = 'rating'
GROUP BY comment_id;
Run Code Online (Sandbox Code Playgroud)

更新:

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;
Run Code Online (Sandbox Code Playgroud)

请注意:请停止使用Mysql_*扩展程序,不推荐使用它们.这样你的代码更容易受到SQL注入攻击.PDO改为使用或准备好的陈述.