mysql - 在mysql中选择行到列

标签 mysql

我有一个如下所示的表格。

**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 请帮忙。

最佳答案

如果 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;

SQL Fiddle

关于mysql - 在mysql中选择行到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32989616/

相关文章:

php - 多次发布数据到 Mysql 数据库

mysql - CiviCRM 4.7.23 升级后出现 SQL 错误

mysql - R RMySQL 查询使日文字符变形

PHP 添加没有字段的列

MySQL 索引列完全还是一一列?

mysql - 使用 union 按查询优化组

mysql - 我可以通过触发器将MySql中的数据插入到MongoDB中吗?

mysql - 如何计算每年销售的产品总量?

php - 将多个表的结果插入一个 json_encode()

MySQL 查询单个表以查找多行