找到没有订购所有3种比萨饼的顾客

时间:2012-11-19 17:28:53

标签: sql oracle sqlplus

customers:
+-----------+-----------+
| cid       | name      |
+-----------+-----------+
| 1         | a         | 
| 2         | b         |
| 3         | c         |
+-----------+-----------+

pizza:
+-----------+-----------+
| pid       | type      |
+-----------+-----------+
| 1         | sausage   |
| 2         | cheese    |
| 3         | veggies   |
| 4         | sausage   |
| 5         | veggies   |
| 6         | sausage   |
| 7         | sausage   |
+-----------+-----------+

orders:
+-----------+-----------+-----------+
| oid       | cid       | pid       |
+-----------+-----------+-----------+
| 1         | 1         | 1         | 
| 2         | 1         | 2         |
| 3         | 2         | 3         |
| 4         | 3         | 4         |
| 5         | 1         | 5         |
| 6         | 3         | 6         |
| 7         | 3         | 7         |
+-----------+-----------+-----------+

我在使用sql逻辑时遇到了一些麻烦。如何找到未订购所有3种披萨的顾客?这三种类型是香肠,奶酪和蔬菜。我需要使用NOT EXIST吗?

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

select c.cid,
  c.name
from customers c
left join orders o
  on c.cid = o.cid
left join pizza p
  on o.pid = p.pid
where p."type" in ('sausage', 'cheese', 'veggies')  -- if you have more pizza types list them here
group by c.cid, c.name
having count(distinct "type") <> (select count(distinct "type")
                                  from pizza)

请参阅SQL Fiddle with Demo

或者

select c.cid,
  c.name
from customers c
left join orders o
  on c.cid = o.cid
left join pizza p
  on o.pid = p.pid
where p."type" in ('sausage', 'cheese', 'veggies')
group by c.cid, c.name
having count(distinct "type") <> 3  -- this is equal to the number of pizza types from the IN clause above

答案 1 :(得分:0)

select cid, count(distinct type) as c from orders join pizza on orders.pid = pizza.pid group by cid having c < 3;