1

首先,您是否看到此代码有问题;

 SELECT num,
        surname, 
        firstname,
        ward 
   FROM doctor, ward WHERE num != consultant;

  NUM SURNAME    FIRSTNAME  W
---------- ---------- ---------- -
  203 Black      Peter      A
  574 Bisi       Mavis      B
  461 Boyne      Steve      B
  530 Clark      Nicola     C
  405 Mizzi      Nicola     A
  501 Mount      Mavis      A
  203 Black      Peter      A

  C NAME       CONSULTANT
  - ---------- ----------
  A Surgical          203
  B Paediatric        574
  C Medical           530

我期望输出是这样的;

 461 Boyne      Steve      B
 405 Mizzi      Nicola     A
 501 Mount      Mavis      A

认为会显示不相等的结果,但是当我执行命令时,结果是这样的;

       NUM SURNAME    FIRSTNAME  W
---------- ---------- ---------- -
       574 Bisi       Mavis      B
       461 Boyne      Steve      B
       530 Clark      Nicola     C
       405 Mizzi      Nicola     A
       501 Mount      Mavis      A
       203 Black      Peter      A
       461 Boyne      Steve      B
       530 Clark      Nicola     C
       405 Mizzi      Nicola     A
       501 Mount      Mavis      A
       203 Black      Peter      A

       NUM SURNAME    FIRSTNAME  W
---------- ---------- ---------- -
       203 Black      Peter      A
       574 Bisi       Mavis      B
       461 Boyne      Steve      B
       405 Mizzi      Nicola     A
       501 Mount      Mavis      A
       203 Black      Peter      A

我对 Oracle 很陌生,所以这可能是一个菜鸟错误,但任何帮助都会很棒。

4

4 回答 4

5

你需要一个左外连接:

 SELECT num,surname, firstname,ward
 FROM doctor left outer join
      ward
      on num = consultant
 WHERE num is null;

您的查询的问题是您正在 和 之间进行笛卡尔积(所有组合doctorward。然后,您将选择两个值不同的行。

编写上述内容的另一种方法可能更清楚:

select d.*
from doctor d
where d.num not in (select consultant from ward);
于 2013-08-09T11:56:11.020 回答
3

这是 SQLFiddel 演示

我认为实现输出的最佳方法是使用not exsits.

以下是您可以尝试的查询

 SELECT *
   FROM doctor
  WHERE not exists (select 1 
                      from ward 
                     where num = consultant)
于 2013-08-09T12:16:18.523 回答
2

您的查询正在创建笛卡尔积,而正确的查询应该是

SELECT num,surname, firstname,ward FROM doctor join ward on (c = w) WHERE num != consultant;
于 2013-08-09T11:56:05.907 回答
1

在您的语句中添加“和 w = C”以构建连接。

或使用

SELECT num,surname, firstname,ward FROM doctor join ward on (c = w) WHERE num != consultant;
于 2013-08-09T11:55:20.420 回答