簡體   English   中英

關於SQL查詢的問題

[英]question about SQL query

我正在開發一個涉及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撰寫的精彩文章,展示了實現關系划分(和變體)的幾種方式: 分裂我們立場:關系划分的SQL

您可以使用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)

恕我直言,比“關系分裂”方法更具可讀性,但效率較低。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM