我有下面的架构。一个简短的解释是:
逻辑:
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吗?从您当前的查询开始,它将是:
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;