2

我一直在玩 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

4 回答 4

1

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

于 2012-05-04T11:36:48.457 回答
0

我不知道您是否有意复制评论行,但如果不是,您可以尝试为这样的评级编写子选择:

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."'
于 2012-05-04T11:40:08.433 回答
0

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

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

于 2012-05-04T11:35:28.623 回答
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. "'"
于 2012-05-04T11:35:43.410 回答