'on子句'中的未知列'R.movi​​e_name'用于内部连接子查询

时间:2017-09-27 05:41:14

标签: mysql join inner-join

我尝试使用join重命名表,但是我遇到了Unknown column 'R.movie_name' in 'on clause'。我引用了这个question来纠正,但我仍然得到同样的错误。

我做错了什么?

我的SQL查询

  SELECT R.movie_name, AVG(S.similarity*R.rating)
 FROM Ratings AS R, Similarity S
 INNER JOIN (
    SELECT DISTINCT R.movie_name
    FROM Ratings R, Users U 
    WHERE U.name = 'Adam Brody' AND U.user_id != R.user_id
    ) AS MoviesAdamDidntWatch ON  R.movie_name = MoviesAdamDidntWatch.movie_name
 GROUP BY R.movie_name;

我的表格

CREATE TABLE Users (user_id INTEGER PRIMARY KEY,
                    name VARCHAR(100) NOT NULL);
CREATE TABLE Ratings (user_id INTEGER NOT NULL,
                      rating INTEGER NOT NULL,
                      movie_name varchar(100) NOT NULL,
                      PRIMARY KEY(user_id, movie_name),
                      FOREIGN KEY (user_id) REFERENCES Users(user_id));
CREATE TABLE Similarity (user1_id INTEGER NOT NULL,
                      user2_id INTEGER NOT NULL,
                      similarity FLOAT,
                      PRIMARY KEY (user1_id, user2_id),
                      FOREIGN KEY (user1_id) REFERENCES Users(user_id),
                      FOREIGN KEY (user2_id) REFERENCES Users(user_id));

1 个答案:

答案 0 :(得分:1)

您在查询中使用了两次R作为别名。你可以通过用其他别名替换外部R来修复它。喜欢 -

SELECT Rtg.movie_name, AVG(S.similarity*Rtg.rating)
 FROM Ratings AS Rtg, Similarity S
 INNER JOIN (
    SELECT DISTINCT R.movie_name
    FROM Ratings R, Users U 
    WHERE U.name = 'Adam Brody' AND U.user_id != R.user_id
    ) AS MoviesAdamDidntWatch ON  Rtg.movie_name = MoviesAdamDidntWatch.movie_name
 GROUP BY Rtg.movie_name;

但是您的查询未经过优化,请考虑通过删除多余的内部查询和跨产品来优化它。如果您发布表结构,我可以帮助您。