sqlite—为什么sql认为我的列名不明确?

axkjgtzd  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(348)

我正在学习sql(lite3),在其中一个练习中,我需要检查imdb数据库中johnny depp和helena bonham carter主演的电影。
我得出了以下结论:

SELECT title 
FROM movies
WHERE movies.id IN (SELECT movies.id  
                    FROM movies
                    JOIN stars ON movies.id = stars.movie_id
                    JOIN people ON people.id = stars.person_id
                    WHERE name = "Jhonny Depp")
  AND movies.id IN (SELECT movies.id 
                    FROM movies
                    JOIN stars ON movies.id = stars.movie_id
                    JOIN people ON people.id = stars.person_id
                    WHERE name = "Helena Bonham Carter");

控制台正在返回
错误:靠近第1行:不明确的列名:id .schema 显示

CREATE TABLE movies 
(
    id INTEGER,
    title TEXT NOT NULL,
    year NUMERIC,
    PRIMARY KEY(id)
);

CREATE TABLE stars 
(
    movie_id INTEGER NOT NULL,
    person_id INTEGER NOT NULL,
    FOREIGN KEY(movie_id) REFERENCES movies(id),
    FOREIGN KEY(person_id) REFERENCES people(id)
);

CREATE TABLE directors 
(
    movie_id INTEGER NOT NULL,
    person_id INTEGER NOT NULL,
    FOREIGN KEY(movie_id) REFERENCES movies(id),
    FOREIGN KEY(person_id) REFERENCES people(id)
);

CREATE TABLE ratings 
(
    movie_id INTEGER NOT NULL,
    rating REAL NOT NULL,
    votes INTEGER NOT NULL,
    FOREIGN KEY(movie_id) REFERENCES movies(id)
);

CREATE TABLE people 
(
    id INTEGER,
    name TEXT NOT NULL,
    birth NUMERIC,
    PRIMARY KEY(id)
);

我不明白为什么它模棱两可。如果你能含糊其辞地把我推向正确的方向,我将不胜感激。提前谢谢!

km0tfn4u

km0tfn4u1#

在主选择中有一个别名。

SELECT m.title FROM movies as m
WHERE movies.id IN
(
    SELECT movies.id FROM movies
    JOIN stars ON movies.id = stars.movie_id
    JOIN people ON people.id = stars.person_id
    WHERE name = "Jhonny Depp"
)
AND movies.id IN
(
    SELECT movies.id FROM movies
    JOIN stars ON movies.id = stars.movie_id
    JOIN people ON people.id = stars.person_id
    WHERE name = "Helena Bonham Carter"
);
hsvhsicv

hsvhsicv2#

嗯。我看不出有什么问题 id . 我看到一个问题 name . 另外,你不需要 movies 在子查询中。所以,你的目标似乎是:

SELECT m.title 
FROM movies m
WHERE m.id IN (SELECT s.movie_id  
               FROM stars s JOIN
                    people p
                    ON p.id = s.person_id
               WHERE p.name = 'Jhonny Depp'
              ) AND
      m.id IN (SELECT s.movie_id  
               FROM stars s JOIN
                    people p
                    ON p.id = s.person_id
               WHERE p.name = 'Helena Bonham Carter'
              );

如果您限定了所有列引用,则不应获得不明确的列引用。请注意表别名的使用。

相关问题