简体   繁体   English

关于SQL查询的问题

[英]question about SQL query

I'm working on a small project involving oracle database, and I have the following tables: 我正在开发一个涉及oracle数据库的小项目,我有以下表格:

CUSTOMER ( Cid, CName, City, Discount )
PRODUCT ( Pid, PName, City, Quantity, Price )
ORDERS ( OrderNo, Month, Cid, Aid, Pid, OrderedQuantity, Cost )

How can retrieve the names of all customers who ordered all the products? 如何检索订购所有产品的所有客户的名称?

For example if customer x ordered product1, product2 and product3 (which are all the products the company offers) he will be selected. 例如,如果客户x订购了product1,product2和product3(这是公司提供的所有产品),他将被选中。 And if customer y only ordered product 1 and 2 but not 3 he will not be selected. 如果客户y仅订购了产品1和2而不是3,则他将不会被选中。

How can I achieve this? 我怎样才能做到这一点?

You want "relational division". 你想要“关系师”。

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);

Here is a great article by Joe Celko that shows several ways of implementing relational division (and variations): Divided We Stand: The SQL of Relational Division 这是一篇由Joe Celko撰写的精彩文章,展示了实现关系划分(和变体)的几种方式: 分裂我们立场:关系划分的SQL

You can use group by and use a having clause to demand that the customer has ordered all products there are: 您可以使用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)

IMHO more readable than the "relational divison" approach, but less efficient. 恕我直言,比“关系分裂”方法更具可读性,但效率较低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM