关于SQL查询的问题

我正在开发一个涉及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,则他将不会被选中.

我怎样才能做到这一点?

你想要“关系师”.

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

相关文章
相关标签/搜索