您可以使用函数或存储过程来解决它,以动态构建整个查询。
The sqlfiddle
我向您展示了如何使用函数 buildQuery,见下文!
创建表事件和数据
create table events (id int, eventtime int);
insert into events values (1, 15);
insert into events values (3, 49);
insert into events values (3, 78);
insert into events values (5, 68);
insert into events values (6, 62);
insert into events values (7, 85);
insert into events values (7, 86);
创建函数 buildQuery()
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(id) as maxevents into maxcols
from events
group by id
order by maxevents desc limit 1;
-- build the query
while counter < maxcols do
set counter = counter + 1;
set query=concat(query,',replace(substring(substring_index(group_concat(eventtime), '','',', counter,'),length(substring_index(group_concat(eventtime),'','',', counter,'-1)) + 1),'','','''') as event' ,counter);
end while;
-- return
return query;
end//
执行函数
set @q = buildQuery();
set @q = concat('select id ', @q, '
from events
group by id');
prepare stmnt from @q;
execute stmnt;
deallocate prepare stmnt;
运行结果
SqlFiddle
The sqlfiddle