我的疑问:
set @sql = NULL;
select
group_concat(distinct
concat(
'max(if(first.study = ''',
study, ''', first.avg_scores, NULL)) as ',
study
)
) into @sql
from `table`;
SET @sql = concat('select first.name,
', @sql, '
from `table` first
join `table` second
on first.name = second.name
group by first.name');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
当列#34;研究"
中的数据时=================================
name | study | avg_scores
=================================
alfa c 75
beta c 70
alfa php 85
beta php 90
和结果:它是真的。
===========================
name | c | php
===========================
alfa 75 85
beta 70 90
当我在表格中有数据时出现问题:
===================================
name | study | avg_scores
===================================
alfa junior c 75
beta junior c 70
alfa junior php 85
beta junior php 90
错误: "您的SQL语法有错误;查看与MySQL服务器版本对应的手册 正确的语法使用近&c; c,max(if(first.study =' junior php', first.avg_scores,NULL))作为初级php'在第2行:从@sql"
准备stmt所以:如何修复我的查询?
答案 0 :(得分:0)
问题是您需要转义标识符,因为列名不能有空格。以下使用名称的双引号(您也可以使用反引号):
set @sql = NULL;
select group_concat(distinct concat('max(if(first.study = ''', study,
''', first.avg_scores, NULL)) as "', study, '"'
---------------------------------------------------------------------^ ----------^
)
) into @sql
from `table`;
SET @sql = concat('select first.name, ', @sql, '
from `table` first join `table` second on first.name = second.name
group by first.name');