数据库
首页 > 数据库> > 如何过滤此MySQL查询,使其仅包含未由特定用户评分的项目?

如何过滤此MySQL查询,使其仅包含未由特定用户评分的项目?

作者:互联网

给定此样本数据集:

item
----
item_id  item_name  item_added
1        Apple      <date_time>
2        Banana     <date_time>

user
----
user_id  user_name
1        Alice
2        Bob
3        Carol

rating
------
rating_id  item_id  user_id  rating_value
1          1        1        3
2          1        2        4
3          1        3        5
4          2        1        5
5          2        2        2

我有此查询来找出哪些项目仅缺少一个评分:

SELECT item.*,
       COUNT(rating_value) AS rating_count
  FROM item
LEFT JOIN rating ON item.item_id = rating.item_id
 GROUP BY item_id
   HAVING rating_count = 2
 ORDER BY item_name

如何修改此查询以显示仅缺少Carol评分的项目? rating_count行不是必需的.唯一必需的列是item_id和item_name.

谢谢.

解决方法:

这将输出仅缺少Carol评分的项目(需要作为参数传递的user_id = 3):

SELECT item.*, COUNT(rating.rating_value) AS rating_count 
 FROM item INNER JOIN rating ON item.item_id = rating.item_id AND 
      (3 NOT IN (SELECT r.user_id FROM rating AS r 
          WHERE r.item_id = rating.item_id))
 GROUP BY item_id
 HAVING rating_count = 2   /* (2 = number of users - 1) */
 ORDER BY item_name;

您必须用电影替换所有项目,但是您的查询将项目和电影混合在一起,并且表是项目,因此我对项目进行了查询,而我在查询中只看到电影为时已晚.

标签:aggregate-functions,sql,mysql
来源: https://codeday.me/bug/20191023/1916599.html