gpt4 book ai didi

php - 高级 MySQL 查询,第 1 组列

转载 作者:行者123 更新时间:2023-11-29 01:38:27 25 4
gpt4 key购买 nike

如果可以的话

我的基地是这样的:

AAA 1
AAA 2
BBB 1
BBB 2
BBB 3

结果一定是这样的

AAA 1   2   
BBB 1 2 3

AAA 1,2 
BBB 1,2,3

发送

最佳答案

使用 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

如果你想用空格分隔( ) 而不是逗号(,),
然后在 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

更新

如果您需要将每个 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

关于php - 高级 MySQL 查询,第 1 组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32781671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com