[英]MySQL JOIN BY to multiple columns
我無法弄清楚以下查詢。
我有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
我想得到以下結果:
Flag Color_1 Color_2 Color_3
----------------------------------------
Belgium Red Yellow Black
France Red White Blue
到目前為止,我有以下幾點:
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
提前致謝。
你可以用一個函數來做到這一點。 如果您不能使用客戶端代碼;)
這是一個解決方案(處理“無限”標志顏色)
構建查詢
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.