gpt4 book ai didi

sql - 为什么这个 SQL 查询不起作用? CS50 Pset7 - 电影

转载 作者:行者123 更新时间:2023-12-01 21:50:04 24 4
gpt4 key购买 nike

我目前正在处理这个 https://cs50.harvard.edu/x/2020/psets/7/movies/并尝试完成 9.sql。

有一个名为“movies”的数据库,包含表:movies(列:id、title、year)、people(id、name、birth)和stars(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;

但是,这只会返回 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一天在类里面做了。他在投影仪上贴了一张箔纸,将一根 pipe 的图像转换到墙上。然后他问:这是什么?

  • 一个人说(可能是我)。
  • 另一个人说的 pipe 图片。
  • 最后,有人说了一个管道投影在墙上的图像。

因为是数据库课,不是物理课,没人敢当机灵鬼。

关于sql - 为什么这个 SQL 查询不起作用? CS50 Pset7 - 电影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59664139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com