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種類すべてのピザを注文しなかった顧客を見つけるにはどうすればよいですか?ソーセージ、チーズ、野菜の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 FiddlewithDemoを参照してください

または

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 に答える