MySQL通过连接到多个列
我无法解决以下查询 我有三张桌子 旗帜 颜色MySQL通过连接到多个列,mysql,Mysql,我无法解决以下查询 我有三张桌子 旗帜 颜色 id color --------------- 1 Red 2 Yellow 3 Blue 4 Black 5 White id flag_id color_id ------------------------ 1 1 1 2 1 2 3 1 4 4 2 1 5 2
id color
---------------
1 Red
2 Yellow
3 Blue
4 Black
5 White
id flag_id color_id
------------------------
1 1 1
2 1 2
3 1 4
4 2 1
5 2 5
6 2 3
旗帜颜色
id color
---------------
1 Red
2 Yellow
3 Blue
4 Black
5 White
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;
结果
这是一个pivot查询,mysql不直接支持它们。您可以在字段列表中使用联接和各种if/case语句,但是这些语句非常难看,速度非常快。做一个标准的查询,在客户端代码中进行行->列转换。非常感谢。是否可以输出生成的查询?(所以要看“s”)。当然!在
准备s..
之前,您可以执行选择@q代码>