为什么这个 SQL 查询不起作用? CS50 Pset7 - 电影
Why is this SQL query not working? CS50 Pset7 - movies
我目前正在处理这个 https://cs50.harvard.edu/x/2020/psets/7/movies/ 并试图完成 9.sql。
有一个名为 "movies" 的数据库,其中包含表格:电影(列:id、标题、年份)、人物(id、姓名、出生)和明星(movie_id、person_id).
任务是:
write a SQL query to list the names of all people who starred in a
movie released in 2004, ordered by birth year. It should return 18,013
names.
到目前为止,这是我所做的:
SELECT count(distinct name)
from people
join stars on stars.person_id = people.id
join movies on stars.movie_id = movies.id
WHERE year = 2004;
然而,这仅 returns 计数 17,965...
谁能看出这是为什么?
如果你count(distinct person_id)
,那么你会得到18013。名称不唯一是合理的。不合理的是考试中的指令说你应该只列出名字。
正确区分名称的一种方法是执行此操作:
SELECT p.name
from people p
where p.id in (
select distinct s.person_id
from stars s join movies m on s.movie_id = m.id
WHERE m.year = 2004)
如果您这样做,那么由于 in
运算符的定义,您甚至不需要 distinct
。但无论如何你可能会得到相同的执行计划。
在我看来,如果 p.name
属于另一个人,则可以多次列出。如果规则以这些词开头,您编写的查询就可以了:
If a person's name ...
而不是这些词:
If a person ...
这让我想起了 C. J. Date 在 class 的一天所做的事情。他在投影仪上贴了一张箔纸,将一根烟斗的图像投射到墙上。他接着问:这是什么?
- 一个人说(可能是我)。
- 另一个人说的烟斗图片。
- 最后,有人说了一个管道投影在墙上的图像。
既然是数据库class而不是物理学class,没人敢当机灵鬼。
我目前正在处理这个 https://cs50.harvard.edu/x/2020/psets/7/movies/ 并试图完成 9.sql。
有一个名为 "movies" 的数据库,其中包含表格:电影(列:id、标题、年份)、人物(id、姓名、出生)和明星(movie_id、person_id).
任务是:
write a SQL query to list the names of all people who starred in a movie released in 2004, ordered by birth year. It should return 18,013 names.
到目前为止,这是我所做的:
SELECT count(distinct name)
from people
join stars on stars.person_id = people.id
join movies on stars.movie_id = movies.id
WHERE year = 2004;
然而,这仅 returns 计数 17,965...
谁能看出这是为什么?
如果你count(distinct person_id)
,那么你会得到18013。名称不唯一是合理的。不合理的是考试中的指令说你应该只列出名字。
正确区分名称的一种方法是执行此操作:
SELECT p.name
from people p
where p.id in (
select distinct s.person_id
from stars s join movies m on s.movie_id = m.id
WHERE m.year = 2004)
如果您这样做,那么由于 in
运算符的定义,您甚至不需要 distinct
。但无论如何你可能会得到相同的执行计划。
在我看来,如果 p.name
属于另一个人,则可以多次列出。如果规则以这些词开头,您编写的查询就可以了:
If a person's name ...
而不是这些词:
If a person ...
这让我想起了 C. J. Date 在 class 的一天所做的事情。他在投影仪上贴了一张箔纸,将一根烟斗的图像投射到墙上。他接着问:这是什么?
- 一个人说(可能是我)。
- 另一个人说的烟斗图片。
- 最后,有人说了一个管道投影在墙上的图像。
既然是数据库class而不是物理学class,没人敢当机灵鬼。