3
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吗?

4

3 回答 3

2

您可以使用一个having子句来查找订购少于 3 种披萨类型的客户:

select  c.name
from    customers c
join    orders c
on      c.cid = c.id
join    pizza p
on      p.id = c.pid
group by
        c.name
having
        count(distinct p.type) < 3
于 2012-11-19T17:36:10.360 回答
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

或者

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
于 2012-11-19T17:40:06.193 回答
0

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

于 2012-11-19T17:41:15.317 回答