对于工程数据库的四张表
厂家 S(SNO,SNAME,STATUS,CITY)
产品P(PNO,PNAME,WEIGHT,COLOR)
工程J(JNO,JNAME,CITY)
供货SPJ(SNO,PNO,JNO,QTY)
一、查询使用了由供应红色产品的厂商供应的产品的工程名
解题步骤:
分为两段解决
- 供应红色产品的厂商,即供应的产品中有产品是红色的:
select sno from spj where spj.pno in( #供应了产品的厂商
select pno from p where color='red') #颜色是红色的产品
- 使用某厂商供应的产品的工程名称,即此工程中用的产品有产品是某厂商供应的:
select jname from j where j.jno in( #使用了某产品的工程名
select spj.jno from spj where spj.sno in(某厂商) #某厂商供应的产品
然后将 某厂商 换为上面的 供应红色产品的产商
就可以得到至少使用了由供应红色产品的厂商供应的产品的工程名
select jname from j where j.jno in(
select spj.jno from spj where spj.sno in(
select sno from spj where spj.pno in(
select pno from p where color='red')
二、查询至少使用了厂家S1所提供的全部零件的工程名
not exists 与双重否定的使用
select * from tt2 where not exists (select * from tt1 where tt1.name=tt2.name);
中 not exists
的意思就是查询tt2表中不存在与tt1表中姓名相同的数据
select jname from j where (
#不存在此零件--厂家S1提供的 and 工程不包含
not exists(
#首先是厂家S1提供的
select * from spj spjx where spjx.sno='S1' and(
#工程不包含--即不存在 工程中的零件与厂家S1提供的相同
not exists(
select * from spj spjy where
#零件与厂家S1提供的相同
spjx.pno =spjy.pno and
#同一个工程中的零件
spjy.jno = j.jno
)))
引用
in的用法:
select * from A where id in(select id from B);
List resultSet=[]; Array A=(select * from A);
Array B=(select id from B);
for(int i=0;i<A.length;i++) {
for(int j=0;j<B.length;j++) {
if(A[i].id==B[j].id) {
resultSet.add(A[i]);
break;
} } }
return resultSet;
exists的用法:
select a.* from A a where exists(select 1 from B b where a.id=b.id);
List resultSet=[];
Array A=(select * from A)
for(int i=0;i<A.length;i++) {
if(exists(A[i].id) { //执行select 1 from B b where b.id=a.id是否有记录返回
resultSet.add(A[i]); } }
return resultSet;
参考
《[Oracle] exists 和 not exists》
《where exists/not exists-----查询选修了全部课程的学生姓名》