2016-03-22 11 views
1

私は把握する次のクエリを取得できません。複数の列にMySQL JOIN BY

私は3つのテーブルを持っています。

国旗

id  flag 
--------------- 
1  Belgium 
2  France 

id color 
--------------- 
1  Red 
2  Yellow 
3  Blue 
4  Black 
5  White 

Flag_Colors私は次のような結果を取得したい

id flag_id color_id 
------------------------ 
1  1  1 
2  1  2 
3  1  4 
4  2  1 
5  2  5 
6  2  3 

事前に

SELECT 
    f.flag, c.color as color_1 
FROM 
    flags f 

LEFT JOIN 
    flag_colors fc 
    ON fc.flag_id = f.id 

LEFT JOIN 
    colors c 
    ON c.id = fc.color_id 

GROUP BY f.id 

ありがとう:

Flag  Color_1 Color_2 Color_3 
---------------------------------------- 
Belgium Red  Yellow  Black 
France Red  White  Blue 

は、これまでのところ、私は次のよう持っています。

+0

ピボットクエリだし、MySQLはそれらを直接サポートしていません。フィールドリストのジョインやさまざまなif/caseステートメントで対処できますが、非常に醜い、非常に速くなります。標準クエリを実行し、クライアント側コードで行→列変換を行います。 –

答えて

1

しかし、それは機能でもできます。あなたは、クライアント側のコードを使用できない場合;)ここで

"無制限" フラグの色

The sqlfiddle

クエリを構築を扱うソリューション(ある

create function buildQuery() returns varchar(4000) 
not deterministic 
reads sql data 
begin 
    -- variables 
    declare query varchar(4000); 
    declare maxcols int; 
    declare counter int; 

    -- initialize 
    set query = ''; 
    set maxcols = 0; 
    set counter = 0; 

    -- get the max amount of columns 
    select count(color_id) as maxflagcolors into maxcols 
    from flag_colors 
    group by flag_id 
    order by maxflagcolors desc limit 1; 

    -- build the query 
    while counter < maxcols do 
    set counter = counter + 1; 
    set query=concat(query,',replace(substring(substring_index(group_concat(c.color), '','',', counter,'),length(substring_index(group_concat(c.color),'','',', counter,'-1)) + 1),'','','''') as color' ,counter);   
    end while; 

    -- return 
    return query; 
end// 

クエリを実行します。

set @q = buildQuery(); 

set @q = concat(
'SELECT 
    f.flag ', @q, ' 
FROM 
    flags f 
LEFT JOIN 
    flag_colors fc 
    ON fc.flag_id = f.id 
LEFT JOIN 
    colors c 
    ON c.id = fc.color_id 
GROUP BY f.id'); 


prepare s from @q; 
execute s; 
deallocate prepare s; 

結果 enter image description here

The sqlfiddle

+1

ありがとうございます。構築されたクエリを出力することは可能ですか? (だから 's'を参照してください)。 –

+0

'prepare s ... 'の前に' select @q; 'を実行することができます。 – MrSimpleMind