admin

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

sql

我有下面的架构。一个简短的解释是:

  1. 鲍勃把这部电影评为5/5
  2. 詹姆斯把电影评为1/5
  3. 梅西把这部电影评为5/5
  4. 没有人评价电影复仇者。

逻辑:

  1. 如果我是personA,请查找我阻止的每个人。
  2. 查找所有电影评论。
  3. 留下电影评论且personA已阻止的任何人,请将其从计算中删除。
  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 |
+-------+------------+

阅读 208

收藏
2021-07-01

共1个答案

admin

你要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;
2021-07-01