如果这是可能高级MySQL查询,组1列
我有在碱这样的:
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
如果这是可能高级MySQL查询,组1列
我有在碱这样的:
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
使用GROUP_CONCAT
。
查询
select column1,
group_concat(column2 separator ',') as column2
from tableName
group by column1;
结果
+---------+---------+
| column1 | column2 |
+---------|---------+
| AAA | 1,2 |
| BBB | 1,2,3 |
+---------+---------+
如果你想与空间()
而不是逗号(,)
分离,
ŧ母鸡在group_concat
中指定separator ' '
。
然后查询将会像下面:
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 |
+---------+---------+---------+---------+
tnx。好。 但如果可能的话:不在一列... –
然后,每个值在不同的列? – Wanderer
使用[GROUP_CONCAT](http://www.w3resource.com/mysql/aggregate-functions-and -grouping/aggregate-functions-and-grouping-group_concat.php) – amdixon
使用group_concat(column2,',')和按列1组 –