ダイナミックで縦列を作成するにはこのスレ
シンプルで手作業でいいんなら
まずサンプルデータを作る
create table user (id int , name varchar(10));
insert into user values
(1,'AA'),
(2,'BB'),
(3,'CC'),
(4,'DD'),
(5,'EE'),
(6,'FF'),
(7,'GG');
create table role (id int ,role varchar(10));
insert into role values
(1,'FW'),(2,'DF'),(3,'GK'),(4,'MF') ;
create table user_role (user_id int ,role_id int);
insert into user_role values
(1,1),(1,2),(2,1),(2,3),(3,4),(4,2),(5,1),(5,2),(6,2),(6,3),(7,1),(7,4);
そしてクエリーは
select
id,
name,
coalesce(max(t.FW),'No') as FW,
coalesce(max(t.DF),'No') as DF,
coalesce(max(t.GK),'No') as GK,
coalesce(max(t.MF),'No') as MF
from user u
left join (
select
case
when r.id = 1 AND ur.role_id is not null then 'Yes'
else null
end `FW`,
case
when r.id = 2 AND ur.role_id is not null then 'Yes'
else null
end `DF`,
case
when r.id = 3 AND ur.role_id is not null then 'Yes'
else null
end `GK`,
case
when r.id = 4 AND ur.role_id is not null then 'Yes'
else null
end `MF`,
user_id
from role r
left join user_role ur on ur.role_id = r.id
)t
on t.user_id = u.id
group by u.id
クエリー結果
ID | NAME | FW | DF | GK | MF |
---|---|---|---|---|---|
1 | AA | Yes | Yes | No | No |
2 | BB | Yes | No | Yes | No |
3 | CC | No | No | No | Yes |
4 | DD | No | Yes | No | No |
5 | EE | Yes | Yes | No | No |
6 | FF | No | Yes | Yes | No |
7 | GG | Yes | No | No | Yes |
質問したURL
http://stackoverflow.com/questions/24425234/how-can-i-get-a-matrix-table-from-two-related-table-by-one-query-statement/24426021#24426021
Abhik Chakrabortyさん、ありがとうございました。
DEMO
クエリーシミュレーション、すげー使えるサイト
http://sqlfiddle.com