我在CS50 2020第7页的电影练习中编写了这段SQLite代码。它是查询号12。目标是找到海伦娜·卡特和约翰尼·德普都出演过的所有电影:
SELECT movies.title FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN (SELECT movies.id FROM movies WHERE name == "Helena Bonham Carter") AND movies.id IN (SELECT movies.id FROM movies WHERE name == "Johnny Depp");
但是这段代码没有输出任何东西。所以我在互联网上得到了一些提示,并写了另一个代码,它的工作正确:
SELECT movies.title FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE movies.id IN (SELECT movies.id FROM movies WHERE name == "Helena Bonham Carter") AND movies.id IN (
SELECT movies.id FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE name == "Johnny Depp");
我还是不明白。如果去掉第一个代码的第二个条件,它会正常工作,并找到海伦娜·卡特出演的所有电影。为什么我必须再次JOIN表格才能为约翰尼·德普制作第二个条件?
1条答案
按热度按时间dgjrabp21#
因为每个
people
行只有一个名称。因此将永远不会返回结果。(尝试选择
name="a" AND name="b"
的任何对象也是如此)