我正在开发一个涉及oracle数据库的小项目, 我有以下表格:
CUSTOMER ( Cid, CName, City, Discount )
PRODUCT ( Pid, PName, City, Quantity, Price )
ORDERS ( OrderNo, Month, Cid, Aid, Pid, OrderedQuantity, Cost )
如何检索订购所有产品的所有客户的名称?
例如,如果客户x订购了product1,product2和product3(这是公司提供的所有产品),他将被选中。如果客户y只订购了产品1和2而不是3,则不会选择它。
我怎样才能做到这一点?
答案 0 :(得分:5)
你想要“关系师”。
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));
或
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撰写的一篇精彩文章,其中介绍了实现关系划分(和变体)的几种方法:Divided We Stand: The SQL of Relational Division
答案 1 :(得分:2)
您可以使用group by
并使用having
子句要求客户订购了所有产品:
select c.CName
from Customers c
join Orders o
on o.Cid = c.Cid
group by
c.Cid
, c.CName
having count(distinct o.Pid) = (select count(*) from products)
恕我直言,比“关系分割”方法更具可读性,但效率较低。