SQL
1create table t_shop(id int primary key,name varchar(30));
2insert into t_shop values
3(1,'店舗1'),
4(2,'店舗2'),
5(3,'店舗3');
6
7create table t_category(id int primary key,name varchar(30));
8insert into t_category values
9(1,'カテゴリー1'),
10(2,'カテゴリー2'),
11(3,'カテゴリー3');
12
13create table t_shop_map(id int primary key,shop_id int,cat_id int,unique(shop_id,cat_id));
14insert into t_shop_map values
15(1,1,1),
16(2,1,2),
17(3,1,3),
18(4,2,1),
19(5,2,2),
20(6,3,3);
カテゴリーが「カテゴリー2」である店舗の一覧を表示
SQL
1select * from t_shop as t2 where exists(
2select 1 from t_shop_map as t1 where exists(
3select 1 from t_category where name='カテゴリー2' and id=t1.cat_id
4) and shop_id=t2.id
5);
各店舗ごとにその店舗が属するカテゴリーも表示する
SQL
1select t1.name,group_concat(t3.name order by t3.id) as categories
2from t_shop as t1
3inner join t_shop_map as t2 on t1.id=t2.shop_id
4inner join t_category as t3 on t2.cat_id=t3.id
5group by name;