我有一张桌子如下所示。
**id | location**
1 | East Flow
2 | East Level
3 | East Pressure
我想在Mysql中使用select语句将上面的表转换如下。
1 | 2 | 3
East Flow | East Level | East Pressure
我正在使用MySql 5.5 请帮忙。
答案 0 :(得分:2)
如果Id列的计数已修复或已知,请使用CASE
表达式。
<强>查询强>
select max(case when id = 1 then location end) as `1`,
max(case when id = 2 then location end) as `2`,
max(case when id = 3 then location end) as `3`
from your_table;
如果id
列的计数未知,则可能需要使用动态sql。
<强>查询强>
select
group_concat(distinct
concat(
'max(case when id = ',
id,' then location end) as `', id,'`'
)
) into @sql
from your_table;
set @sql = concat('select ', @sql, ' from your_table');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;