SQL查询NOT IN,EXIST

架构

Movie(title, year, director, budget, earnings)
Actor(stagename, realname, birthyear)
ActedIn(stagename, title, year, pay)
CanWorkWith(stagename, director)

我需要找到从未在电影中获利的所有演员(舞台名称和真实姓名)(收入>预算).找到所有坏人:P

SELECT A.stagename, A.realname
FROM Actor A
WHERE A.stagename NOT IN
   (SELECT B.stagename
    FROM ActedIN B
    WHERE EXIST 
         (SELECT *
          FROM Movie M
          WHERE M.earnings > M.budget AND M.title = B.title AND M.year))

这会找到其stagename没有出现在第二个查询中的所有actor吗?第二个查询将找到在电影中起作用的所有舞台名称.

它是否正确?

最佳答案

SELECT 
    a.stagename,
    a.realname
FROM
    Actor a
LEFT JOIN
    ActedIn b ON a.stagename = b.stagename
LEFT JOIN
    Movie c ON b.title = c.title 
    AND a.year = b.year 
    AND c.earnings >= c.budget
WHERE 
    c.title IS NULL
GROUP BY
    a.stagename,
    a.realname

– 没有子查询

– 对从未参演过电影的演员的支持

– 根据需要访问聚合函数.

点赞