SQL将表与自身进行比较

时间:2012-06-14 03:45:23

标签: sql

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

查找所有舞台名称对(重命名为stagename1和stagename2),以便演员 stagename1与舞台名2的演员在同一部电影中演出,但收入较少 在那部电影中表演。

SELECT A.stagename, B.stagename
FROM ActedIn A
LEFT JOIN ActedIn B ON A.title = B.title AND A.year = B.year
          AND B.pay > A.pay
WHERE B.name IS NOT NULL

不确定WHERE B.name IS NOT NULL是否有效

2 个答案:

答案 0 :(得分:2)

http://sqlfiddle.com/#!2/67568/1

select a1.stagename as stagename1, a2.stagename as stagename2, a1.title
from ActedIn as a1
 inner join ActedIn as a2 on (a1.title = a2.title and a1.year = a2.year)
where a1.pay < a2.pay

答案 1 :(得分:1)

SELECT A.stagename, B.stagename
FROM ActedIn A
INNER JOIN ActedIn B ON A.title = B.title 
AND A.year = B.year AND B.pay > A.pay
WHERE B.name IS NOT NULL
如果你不想要Bp>的NULL值,那么

LEFT JOIN是没用的