LEFT JOIN的所有行上的SUM()?

时间:2012-05-04 11:30:12

标签: mysql

我一直在玩LEFT JOIN,我想知道是否有可能从下面的查询中获得所有评级的所有评级的总和。以下是关于登录用户是否已评级的信息,但我想显示其他用户的总评分。

$query = mysql_query("
SELECT com.comment, com.comment_id, r.rate_up, r.rate_down
FROM comments com
LEFT JOIN ratings r
ON com.comment_id = r.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'");

我尝试过以下操作,但由于某种原因我只返回一条评论/行。

$query = mysql_query("
SELECT com.comment, com.comment_id,
r.rate_up, r.rate_down 
SUM(r.rate_up) AS total_up_ratings, 
SUM(r.rate_down) AS total_down_ratings,
FROM comments com
LEFT JOIN ratings r
ON com.comment_id = r.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'");

任何帮助表示赞赏。我需要一种不同的JOIN吗?

4 个答案:

答案 0 :(得分:1)

您是否尝试在SQL的末尾使用GROUP BY page_id

答案 1 :(得分:0)

如果在SQL中使用聚合函数(如SUM()),则需要相应的GROUP BY子句。

在您的情况下,最有可能的是com.comment_id;这将为您提供每comment_id的所有评分的总和:

答案 2 :(得分:0)

你可以这样做:

SELECT 
    com.comment, 
    com.comment_id,
    Total.total_down_ratings,
    Total.total_up_ratings
FROM comments com
LEFT JOIN 
(
SELECT
    SUM(r.rate_up) AS total_up_ratings, 
    SUM(r.rate_down) AS total_down_ratings,
    r.comment_id
FROM
    ratings r
GROUP BY
    r.comment_id
) AS Total
ON com.comment_id = Total.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'"

答案 3 :(得分:0)

我不知道你是否为了目的复制了评论行,但如果没有,你可以尝试为这样的评级写下subselect:

select comment_id, user_id, sum(rate_up) as sum_rate_up, 
sum(rate_down) as sum_rate_down from ratings 
group_by comment_id, user_id;

然后将其包含在您的加入查询中:

select com.comment, com.comment_id, r.user_id, r.sum_rate_up, 
r.sum_rate_down from comments com 
left join (select comment_id, user_id, sum(rate_up) as sum_rate_up, 
sum(rate_down) as sum_rate_down from ratings 
group_by comment_id, user_id) as r 
on com.comment_id = r.comment_id where page_id = '".$category_id_var."'