gpt4 book ai didi

Mysql - 基于字段值的连接字段

转载 作者:行者123 更新时间:2023-11-29 04:15:37 25 4
gpt4 key购买 nike

给定一个这样的表:

id     name     field
1 walt a
2 hurley b
3 jack c
4 kate a
5 sawyer a
6 john a
7 ben b
8 miles null
9 juliet c
10 jacob d
11 richard null

你会如何将它转换成这个:

id     ids       names                      field
1 1,4,5,6 walt, kate, sawyer, john a
2 2,7 hurley, ben b
3 8 miles null
4 3,9 jack, juliet c
5 10 jacob d
6 11 richard null

它需要查看具有相同字段值的所有行。然后它需要根据字段值的相等性“合并”所有其他值。但是,如果字段值为 null,则它不应该执行任何操作。

最佳答案

我让这个工作:

mysql> set @x:= 1;

mysql> select group_concat(id) as ids, group_concat(name) as names, field
from `a table like this` group by coalesce(field, @x:=@x+1);
+---------+-----------------------+-------+
| ids | names | field |
+---------+-----------------------+-------+
| 8 | miles | NULL |
| 11 | richard | NULL |
| 1,4,5,6 | walt,kate,sawyer,john | a |
| 2,7 | hurley,ben | b |
| 3,9 | jack,juliet | c |
| 10 | jacob | d |
+---------+-----------------------+-------+

基本上,我欺骗查询将每个 NULL 视为一个非 NULL 值,每次我们评估它时该值都会递增,因此具有 NULL 的每一行都算作一个不同的组。


回复你的评论:

您还可以像这样在查询中初始化一个变量:

select group_concat(id) as ids, group_concat(name) as names, field 
from (select @x:=1) AS _init
cross join `a table like this`
group by coalesce(field, @x:=@x+1);

关于Mysql - 基于字段值的连接字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48999212/

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