MySQL:每个项目的平均评分,使用用户的最新评级

时间:2017-08-14 15:47:13

标签: mysql average greatest-n-per-group

我有items_ratings表如下:

items_ratings
+----+--------+---------+---------+---------------------+
| id | rating | user_id | item_id | created (DATETIME)  |
+----+--------+---------+---------+---------------------+
| 1  | 20     | 1       | 12      | 2017-07-12 14:00:04 |
| 2  | 80     | 2       | 12      | 2017-07-12 15:32:12 |
| 3  | 50     | 1       | 15      | 2017-08-01 11:14:04 |
| 4  | 90     | 1       | 12      | 2017-08-02 19:23:19 |
| 5  | 60     | 2       | 15      | 2017-08-05 19:23:19 |
+----+--------+---------+---------+---------------------+

我需要使用每个用户最近的评分来检索每item_id的平均值。

以下是每个项目的平均评分:

SELECT AVG(rating) FROM items_ratings
GROUP BY item_id

我还发现以下查询为user_id提供了每个item_id的最新行。

SELECT MAX(created), user_id, item_id FROM items_ratings
GROUP BY user_id, item_id;

我不确定如何组合这些查询以产生我想要的结果。

1 个答案:

答案 0 :(得分:1)

您可以使用select from join table with user by user_id

  select item_id, avg( rating) from (
      select * from items_ratings  a 
      inner join (
      SELECT MAX(created) t_created, user_id
      FROM items_ratings
      GROUP BY user_id
        ) t on  t.user_id = a.user_id and t.t_created = a.created 
      ) t1
  group by item_id

内部选择获取user_id创建的最大值,另一个获取macht的所有行,外部通过item_id获取此组上的平均值

使用item_id上的新条件,您可以使用

   select item_id, avg( rating) from (
      select * from items_ratings  a 
      inner join (
      SELECT MAX(created) t_created, user_id, item_id
      FROM items_ratings
      GROUP BY user_id, item_id
        ) t on  t.user_id = a.user_id and  t.t_created = a.created  and  t.item_id = a.item_id
      ) t1
  group by item_id