對於工程數據庫的四張表
廠家 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-----查詢選修了全部課程的學生姓名》