You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50作业7中这条无输出的SQL语句存在什么问题?

你的SQL语句问题分析&修正方案

让我来帮你拆解下为什么这个SQL执行后没有输出——核心问题出在内层INTERSECT的使用逻辑错误!

问题根源

你内层的子查询:

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

这个语句的意图是找「同时叫Johnny Depp和Helena Bonham Carter的人的ID」,但现实中一个人不可能拥有两个完全不同的全名,所以这个子查询必然返回空集。外层的where id in (...)没有任何匹配的ID,自然查不到任何电影结果。

正确思路&修正方案

你真正想要的是「同时有Johnny Depp和Helena Bonham Carter参演的电影」,应该在电影ID的层面取交集,而不是在人物ID层面。下面给你几种可行的修正写法:

方案1:用INTERSECT在电影ID层面(支持该语法的数据库如PostgreSQL、SQL Server等适用)

select title 
from movies 
where id in (
    -- 先找Johnny Depp参演的所有电影ID
    select movie_id from stars where person_id = (select id from people where name = "Johnny Depp")
    intersect
    -- 再找Helena参演的所有电影ID,取交集
    select movie_id from stars where person_id = (select id from people where name = "Helena Bonham Carter")
);

方案2:用分组+COUNT筛选(通用型,几乎所有数据库都支持)

select m.title
from movies m
join stars s on m.id = s.movie_id
join people p on s.person_id = p.id
where p.name in ("Johnny Depp", "Helena Bonham Carter")
group by m.id, m.title
-- 确保该电影同时有两位演员参演
having count(distinct p.id) = 2;

方案3:用双重EXISTS子查询(逻辑清晰,性能也不错)

select title
from movies m
where exists (
    -- 检查该电影有Johnny Depp参演
    select 1 from stars s1
    join people p1 on s1.person_id = p1.id
    where s1.movie_id = m.id and p1.name = "Johnny Depp"
)
and exists (
    -- 同时检查该电影有Helena参演
    select 1 from stars s2
    join people p2 on s2.person_id = p2.id
    where s2.movie_id = m.id and p2.name = "Helena Bonham Carter"
);

额外注意点

如果修正后还是没有结果,你可以先单独检查以下几点:

  • people表中是否真的存在这两个名字的记录?注意大小写、空格或拼写错误(比如名字是否完全匹配)
  • stars表中是否有这两位演员对应的参演记录?

内容的提问来源于stack exchange,提问作者user12069108

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 13:32:48