SQL Where not exists双重否定例子分析
以下面的例子来说吧有顾客表customers(CNO, CNAME, SEX, AGE),书籍表books(BNO,BNAME, PNO, PRICE),出版社表publisher(PNO, PUBNAME,ADDRESS),购买表buy(CNO,BNO, DATE)。先要查找所有顾客(谁购买了所有清华社出版出版的书)的编号。SQL语句:
以下面的例子来说吧
有顾客表customers(CNO, CNAME, SEX, AGE),
书籍表books(BNO,BNAME, PNO, PRICE),
出版社表publisher(PNO, PUBNAME,ADDRESS),
购买表buy(CNO,BNO, DATE)。
先要查找所有顾客(谁购买了所有清华社出版出版的书)的编号。
SQL语句:
select CNO
from customers
where not exists(
select *
from book
where PNO in(select PNO
from publisher
where PUBNAME = ‘清华大学出版社’)
and
not exists
(select *
from buy
where BNO = books.BNO
and CNO = customers.CNO))
先看
not exists
select *
from buy
where BNO = books.BNO
and CNO = customers.CNO
可以这样理解,它表示的意思:选取所有买书的人。再加上not exists呢?就是选取没有买书的人 ,没有买什么样的书呢?
接着看
select *
from book
where PNO in(select PNO
from publisher
where PUBNAME = ‘清华大学出版社’)
这个select意思是啥?选取所有清华大学出版社出版的书,
and以后呢 就变成了:“没有买所有清华大学出版社出版的书的人”,外面又加了一个 where not exists,这样的情况不存在,那不就成了:“有买所有清华大学出版社出版的书的人 ” 了吗?,然后再把他们的编号选出来:
select CNO
from customers
我这里的想法是先假设题目要求的设这个人一定存在
更多推荐
所有评论(0)