LoginSignup
0
0

More than 3 years have passed since last update.

商品マスタの全ての商品を持つ店舗を取得する

Posted at

以下のテーブルがある

select * from items;
+--------------+
| item         |
+--------------+
| ビール       |
| 紙オムツ     |
| 自転車       |
+--------------+
select * from shopitems;
+--------+--------------+
| shop   | item         |
+--------+--------------+
| 仙台   | カーテン     |
| 仙台   | ビール       |
| 仙台   | 紙オムツ     |
| 仙台   | 自転車       |
| 大阪   | テレビ       |
| 大阪   | 紙オムツ     |
| 大阪   | 自転車       |
| 東京   | ビール       |
| 東京   | 紙オムツ     |
| 東京   | 自転車       |
+--------+--------------+

shopitemsテーブルでshopテーブルの全てのitemを持つshopを取得する。(仙台、東京)

select
si.shop
from
shopitems si
,items i
where
si.item = i.item
group by
si.shop
having
count(si.item) = (
    select
    count(item)
    from
    items
);

+--------+
| shop   |
+--------+
| 仙台   |
| 東京   |
+--------+

仙台にはitemsテーブルにないカーテンもある状態。
仙台を除く場合は以下。

select
si.shop
from
shopitems si
left outer join
items i
on si.item = i.item
group by
si.shop
having
count(si.item) =
(
    select
    count(*)
    from
    items
)
and count(i.item) = 
(
    select
    count(*)
    from
    items
);

こちらを参考にさせていただきました。
達人に学ぶSQL徹底指南書 第2版 初級者で終わりたくないあなたへ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0