如何根据条件删除结果以计算平均和特定电影

How do I remove results based on conditions to calculate an average and specific movie

我有下面的架构。对其的快速解释是:

  1. 鲍勃给这部电影打了 5/5
  2. 詹姆斯给这部电影打了 1/5
  3. macy 对这部电影的评分为 5/5
  4. 没有人评价电影复仇者联盟。

逻辑:

  1. 如果我是 A 人,请查看我屏蔽的所有人。
  2. 查找所有电影评论。
  3. 任何留下影评的人,被 A 屏蔽的人,将他们从计算中移除。
  4. 计算电影的平均评分。

CREATE TABLE movies (
  id integer AUTO_INCREMENT primary key,
  name varchar(100) NOT NULL
);

CREATE TABLE customer (
  id integer AUTO_INCREMENT primary key,
  name varchar(100) NOT NULL
);

CREATE TABLE reviews (
  id integer AUTO_INCREMENT primary key,
  rating integer NOT NULL,
  cus_id integer NOT NULL,
  movie_id integer NOT NULL,
  FOREIGN KEY (cus_id) REFERENCES customer(id),
  FOREIGN KEY (movie_id) REFERENCES movies(id)
);

CREATE TABLE blocked(
  id integer AUTO_INCREMENT primary key,
  cus_id integer NOT NULL, -- This is the person blocking
  blocked_cus_id integer NOT NULL, -- This is the person who is blocked
  FOREIGN KEY (cus_id) REFERENCES customer(id),
  FOREIGN KEY (blocked_cus_id) REFERENCES customer(id)
);

INSERT INTO movies (id, name) VALUES (1, 'up'), (2, 'avengers');
INSERT INTO customer (id, name) VALUES (1, 'bob'), (2, 'james'), (3, 'macy');
INSERT INTO reviews (id, rating, cus_id, movie_id) VALUES (1, 5, 1, 1), (2, 1, 2, 1), (3, 5, 3, 1);
INSERT INTO blocked (id, cus_id, blocked_cus_id) VALUES (1, 1, 2);

我在这里得到了一些关于这个问题的帮助:(并且声明是正确的)但是当我想找到特定电影的评级时,声明只显示有评级的电影.我希望它显示电影,无论它是否有评级。如果它没有评级,它应该只说 0。下面,电影复仇者联盟没有评级,也没有显示任何结果。

SELECT m.name, AVG(r.rating) AS avg_rating
FROM movies m
INNER JOIN reviews r ON m.id = r.movie_id
WHERE NOT EXISTS (SELECT 1 FROM blocked b
                  WHERE b.blocked_cus_id = r.cus_id AND b.cus_id = 1)
AND m.id = 2
GROUP BY m.name;

上面的select语句应该显示:

+----------+------------+
| movie    | avg_rating |
+----------+------------+
| avengers |          0 |
+----------+------------+

当我以 bob 的身份查看数据库时,我应该得到:

+-------+------------+
| movie | avg_rating |
+-------+------------+
| up    |          5 |
+-------+------------+

当我查看数据库为 macy 时,我应该得到:

+-------+------------+
| movie | avg_rating |
+-------+------------+
| up    |       3.67 |
+-------+------------+

你想要left join吗?从您当前的查询开始,那将是:

SELECT m.name, AVG(COALESCE(r.rating, 0)) AS avg_rating
FROM movies m
LEFT JOIN reviews r 
    ON m.id = r.movie_id
    AND NOT EXISTS (
        SELECT 1 
        FROM blocked b
        WHERE b.blocked_cus_id = r.cus_id AND b.cus_id = 1
    )
WHERE m.id = 2
GROUP BY m.id, m.name;