我使用“使用组”编写“查找只进行一次预订的sids”查询,具体如下:
SELECT R.sid
FROM Sailors S,
Reserve R
WHERE R.sid = S.sid
GROUP BY R.sid
HAVING Count(R.sid) = 1
但我想通过使用(不存在)命令找到它。我写了
SELECT S.sid
FROM Sailors S
WHERE NOT EXISTS (SELECT R.sid
FROM Reserve R
WHERE Count(R.sid) <> 1)
但它有错误。如何使用not exists命令编写它。
答案 0 :(得分:2)
如果Reserve有一个主键,你可以这样写:
Select
s.sid
From
Sailors s
Inner Join
Reserve r
On s.sid = r.sid
Where
Not Exists (
Select
'x'
From
Reserve r2
Where
r2.sid = s.sid And
r2.rid != r.rid
);
注意,在这种情况下,您甚至不需要引用Sailors表:
Select
r.sid
From
Reserve r
Where
Not Exists (
Select
'x'
From
Reserve r2
Where
r2.sid = r.sid And
r2.rid != r.rid
);