MySQL按计数+值的总和选择

时间:2011-03-11 03:43:43

标签: mysql count comments

我有以下查询(Wordpress DB)。

这将返回具有最多组合“向上”和“向下”评级的评论的数据:

$comment_query = $wpdb->get_results("
SELECT wp_comments.*, wp_comment_rating.*, (wp_comment_rating.ck_rating_up+wp_comment_rating.ck_rating_down) AS pop_comment 
FROM wp_comments, wp_comment_rating 
WHERE wp_comments.comment_post_ID = $post->ID 
AND wp_comments.comment_ID = wp_comment_rating.ck_comment_id 
AND wp_comments.comment_approved = 1 
ORDER BY pop_comment 
DESC 
LIMIT 1");

但是,我还想通过计算每个评论的匹配“comment_parent”的数量,然后将该总数添加到我正在排序的“pop_comment”值来考虑回复最多的评论。

基本上,我想获得评论的数据,其中包含最多的回复和上/下评级。

希望有道理......

2 个答案:

答案 0 :(得分:0)

您可以通过comment_parent

获取子查询来获取计数
$comment_query = $wpdb->get_results("
SELECT wp_comments.*, wp_comment_rating.*, (wp_comment_rating.ck_rating_up+wp_comment_rating.ck_rating_down + (
    select count(*) from wp_comments c2 where c2.comment_parent=wp_comments.comment_ID
    )) AS pop_comment 
FROM wp_comments, wp_comment_rating 
WHERE wp_comments.comment_post_ID = $post->ID 
AND wp_comments.comment_ID = wp_comment_rating.ck_comment_id 
AND wp_comments.comment_approved = 1 
ORDER BY pop_comment 
DESC 
LIMIT 1");

答案 1 :(得分:0)

这应该有效

基本上它只是一个子查询来获取comment_parent的总注释,然后将其作为SubQ / SubCount加入到字段中

comment_query = $wpdb->get_results(" 
SELECT wp_comments.*, wp_comment_rating.*, (SubCount + pop_comment) AS total_rank,    (wp_comment_rating.ck_rating_up+wp_comment_rating.ck_rating_down) AS pop_comment  
JOIN (SELECT COUNT(*) as SubCount, comment_parent as Sub_ID FROM wp_comments GROUP BY comment_parent) as SubQ
ON wp_comments.comment_ID = SubQ.Sub_ID
FROM wp_comments, wp_comment_rating  
WHERE wp_comments.comment_post_ID = $post->ID  
AND wp_comments.comment_ID = wp_comment_rating.ck_comment_id  
AND wp_comments.comment_approved = 1  ORDER BY total_rank  DESC  LIMIT 1");