2

我有下表

id item_id rating 
 1    10     1
 2    10     2
 3    10     2
 4    10     3
 5    10     3
 6    10     3
 7    10     4

如何编写查询以便获得如下结果:

$ratings = array(
    1 => 1,
    2 => 2,
    3 => 3,
    4 => 1,
    5 => 0
);

我需要使用这个查询来编写一个 php 函数来计算这个函数的平均评分:

$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
  $total += $number * $frequency;
  $count += $frequency;
}
return $total / $count;
4

2 回答 2

3
SELECT
    rating,
    COUNT(rating) as Count
FROM rating
GROUP BY rating 
于 2013-01-30T08:18:58.580 回答
3

表上的记录基本COUNT不会产生5,因为评级没有价值5。但是生成包含来自的值1-5并使用它们连接它们的子查询LEFT JOIN将达到您想要的结果。

SELECT a.rating, COUNT(b.rating) totalCount
FROM
    (
      SELECT 1 rating UNION SELECT 2 UNION
      SELECT 3 UNION SELECT 4 UNION
      SELECT 5
    ) a
    LEFT JOIN tableName b
      ON a.rating = b.rating
GROUP BY a.rating
于 2013-01-30T08:19:12.440 回答