我有一个课堂作业,并且有作业的答案,它与我的答案不匹配,但是对我来说,它看起来会返回相同的内容。我想知道这是否是真的。
以下是架构:
Supplier
(sid,sname,城市)Part
(部件号,部件名)Project
(projid,projname,城市)Supply
(sid,projid,partid,amount)这里的问题是:使用projid = 1列出不为该项目提供产品的那些供应商的名称。
我的代码:
select Supplier.sname
from Supplier
join Supply on Supplier.sid = Supply.sid
join Project on Supply.projid = Project.projid
where not projid = 1;
教授的代码:
Select sname
from Supplier
Minus
(Select sname
from supplier
Join Supply on Supplier.sid = Supply.sid
Where projid = '1');
这些返回的结果是否相同?
答案 0 :(得分:3)
您的代码错误。
1
的供应商,前提是他们还提供了至少一个其他项目。您想隐藏这样的供应商。Supply
表中的每个条目重复供应商的名称。您需要一个没有重复的名称列表。教授的密码是正确的。
答案 1 :(得分:0)
GSerg的答案已经解释了它。
但是我认为查看SQL是否按预期运行的一种方法是使用示例数据运行它们。
Oracle DB的MINUS
表运算符的作用与ANSI SQL标准EXCEPT DISTINCT
相同。
因此,下面的测试对第二个查询使用EXCEPT
。
第一个查询不返回“ Buns Of Moe Bakery”,因为它仅针对项目1进行交付。
第二个带有EXCEPT
的查询仅返回'Gringotts',因为它是唯一也不为项目1交付的供应商。
CREATE TABLE TestSupplier ( sid int primary key, sname varchar(30) not null );
CREATE TABLE TestProject ( projid int primary key, projname varchar(30) not null );
CREATE TABLE TestSupply ( supplyid int primary key, sid int, projid int, supplyname varchar(30) not null, foreign key (sid) references TestSupplier(sid), foreign key (projid) references TestProject(projid) );
INSERT INTO TestSupplier (sid, sname) VALUES (101,'ACME Corp.'), (102,'Gringotts'), (103,'Buns Of Moe Bakery');
INSERT INTO TestProject (projid, projname) VALUES (1,'Unite the World'), (2,'Gate To Isekai');
INSERT INTO TestSupply (supplyid, sid, projid, supplyname) VALUES (301,101,1,'Global Brainwash Device'), (302,101,2,'Industrial Space Food'), (303,102,2,'Magic Circle'), (304,103,1,'Donuts');
-- Only rejects suppliers that only deliver supplies for project 1 select distinct Supplier.sname from TestSupplier as Supplier join TestSupply as Supply on Supplier.sid = Supply.sid join TestProject as Project on Supply.projid = Project.projid where not Project.projid = 1;
| sname | | :--------- | | ACME Corp. | | Gringotts |
-- All suppliers without those that also supply to project 1 select distinct sname from TestSupplier except select distinct Supplier.sname from TestSupplier AS Supplier join TestSupply AS Supply ON Supply.sid = Supplier.sid where Supply.projid = 1;
| sname | | :-------- | | Gringotts |
db <>提琴here