-1

我使用 Using group 编写了“查找仅做了一次预订的 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 命令编写它。

4

1 回答 1

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
  );

http://sqlfiddle.com/#!3/cce6c/2

于 2012-11-11T11:37:31.503 回答