首先,您是否发现此代码存在问题;
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很新鲜,所以这可能是一个noob错误,但任何帮助都会很棒。
答案 0 :(得分:5)
您需要左外连接:
SELECT num,surname, firstname,ward
FROM doctor left outer join
ward
on num = consultant
WHERE num is null;
您的查询存在的问题是,您正在doctor
和ward
之间进行笛卡尔积(所有组合)。然后,您将选择两个值不同的行。
写上述内容的另一种方法可能更清楚:
select d.*
from doctor d
where d.num not in (select consultant from ward);
答案 1 :(得分:3)
<强> Here is the SQLFiddel Demo 强>
我认为实现输出的最佳方法是使用not exsits
。
以下是您可以尝试的查询
SELECT *
FROM doctor
WHERE not exists (select 1
from ward
where num = consultant)
答案 2 :(得分:2)
您的查询正在创建笛卡尔积 而正确的查询应该是
SELECT num,surname, firstname,ward FROM doctor join ward on (c = w) WHERE num != consultant;
答案 3 :(得分:1)
在语句中添加“和w = C”以构建连接。
或使用
SELECT num,surname, firstname,ward FROM doctor join ward on (c = w) WHERE num != consultant;