关于SQL查询的问题

Sar*_*ara 4 sql oracle

我正在开发一个涉及oracle数据库的小项目,我有以下表格:

CUSTOMER ( Cid, CName, City, Discount )
PRODUCT ( Pid, PName, City, Quantity, Price )
ORDERS ( OrderNo, Month, Cid, Aid, Pid, OrderedQuantity, Cost )
Run Code Online (Sandbox Code Playgroud)

如何检索订购所有产品的所有客户的名称?

例如,如果客户x订购了product1,product2和product3(这是公司提供的所有产品),他将被选中.如果客户y仅订购了产品1和2但未订购3,则不会选择.

我怎样才能做到这一点?

Ron*_*nis 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));
Run Code Online (Sandbox Code Playgroud)

要么

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);
Run Code Online (Sandbox Code Playgroud)

这是一篇由Joe Celko撰写的精彩文章,展示了实现关系划分(和变体)的几种方式:分裂我们立场:关系划分的SQL