表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……复仇者
你能帮我吗?
您可以在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
)
)
这个查询读起来几乎像一个结构拙劣的英语句子,但它解释了发生了什么。
试试这个,
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
从您的示例数据集中可以清楚地看出,您需要表C中存在租金的dvd。为此,您可以执行简单的INNER
联接,表3中的最后一个联接将满足表1 中dvd的租金存在条件
select t1.* FROM
Table1 t1
LEFT JOIN Table2 USING(dvdID)
JOIN Table3 USING(rentID)
Fiddle演示
试试这个选项1
select * from A
where dvdID not in (Select dvdID from B where rentID not in (select rentID from C))
您应该使用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)
试试这个:
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)