简体   繁体   English

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

[英]Why is this SQL query not working? CS50 Pset7 - movies

I'm currently working through this https://cs50.harvard.edu/x/2020/psets/7/movies/ and trying to complete 9.sql.我目前正在通过这个https://cs50.harvard.edu/x/2020/psets/7/movies/并尝试完成 9.sql。

There a database called "movies", with tables: movies (columns: id, title, year), people (id, name, birth) and stars (movie_id, person_id).有一个名为“电影”的数据库,其中包含表:电影(列:id、标题、年份)、人物(id、姓名、出生)和明星(movie_id、person_id)。

The task is:任务是:

write a SQL query to list the names of all people who starred in a movie released in 2004, ordered by birth year.编写一个 SQL 查询来列出所有出演 2004 年上映的电影的人的名字,按出生年份排序。 It should return 18,013 names.它应该返回 18,013 个名字。

So far, this is what I've done:到目前为止,这就是我所做的:

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;

However, this only returns a count of 17,965...但是,这仅返回 17,965 的计数......

Can anyone see why this might be?谁能看出为什么会这样?

If you count(distinct person_id) , then you will get 18013. It's reasonable that name is not unique.如果您count(distinct person_id) ,那么您将得到 18013。名称不唯一是合理的。 What is unreasonable is the directive in the exam saying you should list only name.不合理的是考试中的指令说你应该只列出姓名。

One way to correctly distinct the names is to execute this:正确区分名称的一种方法是执行以下操作:

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)

And if you do it that way, then you don't even need the distinct due to the definition of the in operator.如果你这样做,那么由于in运算符的定义,你甚至不需要distinct But you probably will get the same execution plan regardless.但无论如何,您可能会得到相同的执行计划。

It's ok, in my opinion, to list a p.name more than once if it belongs to another person.在我看来,如果某个p.name属于另一个人,则可以多次列出它。 The query you wrote would have been ok if the rule started with these words:如果规则以这些词开头,您编写的查询就可以了:

If a person's name ...如果一个人的名字...

instead of these words:而不是这些词:

If a person ...如果一个人...

Which reminds me of something CJ Date did in class one day.这让我想起了CJ Date有一天在课堂上做的一件事。 He put a foil on his projector that projected an image of a smoking pipe on the wall.他在他的投影仪上放了一张箔片,在墙上投射出一张烟斗的图像。 He then asked: what is this?他接着问:这是什么?

  • A pipe, one guy said (probably me).一个管子,一个人说(可能是我)。
  • An image of a pipe another guy said.另一个人说的管子的图像。
  • Finally, someone said an image of a pipe projected on a wall.最后,有人说投影在墙上的管道图像。

Since it was a database class and not a physics class, nobody dared to be a smart-a**.既然是数据库课,不是物理课,谁也不敢当smart-a**。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM