表A:
dvdID ....... dvdTitle
D01 ..........复仇者
D02 ..........复仇者
D03 ..........蜘蛛侠
表B:
rentID ....... dvdID
R01 ........... D01
R02 ........... D02
R03 ........... D03
表C:
returnID ....... rentID
T01 ............... R01
我想选择不在表B(租用)中的DVD,除了表C中的(返回) 所以输出应该是这样的:
输出:
你可以帮助我吗?dvdID ....... dvdTitle
D01 ..........复仇者
答案 0 :(得分:3)
您可以在SQL条件中使用存在量词,由EXISTS
关键字表示:
SELECT *
FROM TableA a
WHERE NOT EXISTS ( -- No rental record
SELECT *
FROM TableB b
WHERE b.dvdID=a.dvdID -- The record is for this DVD, and...
AND NOT EXISTS ( -- ...there is no return record
SELECT * FROM TableC c WHERE c.rentID=b.rentID
)
)
查询读起来几乎就像一个构造不好的英语句子,但它解释了发生了什么。
答案 1 :(得分:1)
试试这个,
SELECT *
FROM A
WHERE (NOT EXISTS (SELECT * FROM B WHERE B.dvdID=A.dvdID))
OR (EXISTS (SELECT * FROM C,B WHERE C.rentID=B.rentID and B.dvdID=A.dvdID))
这里是SQLFiddle
答案 2 :(得分:1)
从您的示例数据集中可以清楚地看到,您需要在TableC中存在租金的dvds,这样您就可以进行简单的INNER
连接,来自table3的最后一次连接将满足dvd的租金存在条件表1
select t1.* FROM
Table1 t1
LEFT JOIN Table2 USING(dvdID)
JOIN Table3 USING(rentID)
答案 3 :(得分:1)
试试这个 备选方案1
select * from A
where dvdID not in (Select dvdID from B where rentID not in (select rentID from C))
答案 4 :(得分:0)
试试这个:
SELECT TableA.dvdID, TableA.dvdTitle
FROM TableA
LEFT JOIN TableB ON TableA.dvdID = TableB.dvdID
LEFT JOIN TableC ON TableC.rentID = TableB.rentID
WHERE TableB.rentID IS NULL
OR (TableB.rentID IS NOT NULL
AND TableC.returnID IS NOT NULL)
答案 5 :(得分:0)
您应该使用JOINS
代替EXISTS / NOT EXISTS
SELECT
a.*
FROM TableA a
LEFT join TableB b
on b.id=a.id
LEFT Join TableC c
on c.id=a.id
WHERE
b.id is null
OR (b.id is not null AND c.id is not null)