【问题标题】:What is wrong with this SQL statement for cs50 problem set 7?cs50 题集 7 的这条 SQL 语句有什么问题?
【发布时间】:2020-04-29 13:38:23
【问题描述】:

这句话有什么问题?结果是没有输出。

select title from movies where id in 
(select movie_id from stars where person_id in 
(select id from people where name="Johnny Depp" intersect 
select id from people where name="Helena Bonham Carter"));

【问题讨论】:

  • 应该连语法都没有,mysql中没有intersect,搜索mysql intersect寻找替代方案。
  • CS50 使用 sqlite,而不是 mysql。
  • 您的语法有问题。使用 intersect,您需要构建两个 SQL 查询。检查本网站的使用情况; sqlitetutorial.net/sqlite-intersect
  • 以下语句有效: select title from movies where id in (select movie_id from stars where person_id in (select id from people where name="Johnny Depp") intersect select movie_id from stars where person_id in (从 name="Helena Bonham Carter")) 的人中选择 id;

标签: sql sqlite cs50 intersect


【解决方案1】:

此声明:

select id from people where name="Johnny Depp" 
intersect 
select id from people where name="Helena Bonham Carter"

返回 2 个查询的 common 结果,但由于 id 是表 people 的唯一主键,因此它不会返回任何内容。
更简单:如果第一个查询返回 10,第二个返回 20,则 10 和 20 的交集不存在。
您可以通过连接获得所需的结果:

select distinct m.title
from movies m
inner join stars s1 on s1.movie_id = m.id 
inner join stars s2 on s2.movie_id = m.id 
inner join people p1 on p1.id = s1.person_id and p1.name = 'Johnny Depp'
inner join people p2 on p2.id = s2.person_id and p2.name = 'Helena Bonham Carter'

【讨论】:

  • 很好的解释。 mafter movies 是别名?
  • 是的,每个表都需要一个别名。
猜你喜欢
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 2011-08-28
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多