我正在做一个涉及oracle数据库的小项目,
我有下表:
CUSTOMER ( Cid, CName, City, Discount )
PRODUCT ( Pid, PName, City, Quantity, Price )
ORDERS ( OrderNo, Month, Cid, Aid, Pid, OrderedQuantity, Cost )
如何检索订购所有产品的所有客户的姓名?
例如,如果客户 x 订购了产品 1、产品 2 和产品 3(这是公司提供的所有产品),他将被选中。如果客户 y 只订购了产品 1 和 2 而没有订购 3,那么他将不会被选择。
我怎样才能实现这个目标?
你想要“关系划分”。
select *
from customer c
where not exists( -- There are no product
select 'x'
from product p
where not exists( -- the customer did not buy
select 'x'
from orders o
where o.cid = c.cid
and o.pid = p.id));
or
select c.cid
,c.name
from customer c
join orders o using(cid)
group
by c.id
,c.name
having count(distinct o.pid) = (select count(*) from product);
这是 Joe Celko 撰写的一篇精彩文章,展示了实现关系划分(及其变体)的几种方法:我们立场分歧:关系划分的 SQL http://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)