高级MySQL查询,第1组列

时间:2015-09-25 11:55:41

标签: php mysql

如果可能的话

我有这样的基础:

AAA 1
AAA 2
BBB 1
BBB 2
BBB 3

,结果必须像这样

AAA 1   2   
BBB 1   2   3

AAA 1,2 
BBB 1,2,3

TNX

1 个答案:

答案 0 :(得分:4)

使用GROUP_CONCAT

<强>查询

select column1,
group_concat(column2 separator ',') as column2
from tableName
group by column1;

<强>结果

+---------+---------+
| column1 | column2 |
+---------|---------+
| AAA     | 1,2     |
| BBB     | 1,2,3   |
+---------+---------+

SQL Fiddle

如果您想要用空格( )而不是逗号(,)分隔,
然后在separator ' '中指定group_concat

然后查询将如下所示:

select column1,
group_concat(column2 separator ' ') as column2
from tableName
group by column1;

<强>结果

+---------+---------+
| column1 | column2 |
+---------|---------+
| AAA     | 1 2     |
| BBB     | 1 2 3   |
+---------+---------+

Read more about group_concat here

UPDATE

如果您需要单独列中的每个column2值, 那么您可能需要执行动态SQL查询。

<强>查询

set @query = null;
select
group_concat(distinct
    concat(
      'max(case when column2 = ''',
      column2, ''' then column2 end) as Value_',column2
    )
  ) into @query
from tableName ;

set @query = concat('select column1, ', @query, ' from tableName 
                  group by column1
');

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

<强>结果

+---------+---------+---------+---------+
| column1 | Value_1 | Value_2 | Value_3 |
+---------+---------+---------+---------+
| AAA     |  1      |  2      | (null)  |
| BBB     |  1      |  2      | 3       |
+---------+---------+---------+---------+

SQL Fiddle