繁体   English   中英

MySQL-基于字段值的Concat字段

[英]Mysql - Concat fields based on value of field

给定这样一个表:

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);

GROUP_CONCAT可用于将来自不同行的数据聚合到一个连接字符串中(顾名思义); 它还支持自己的ORDER BY子句,因此您需要确保相应的值最终位于list *的相同相对位置。

SELECT MIN(id)
   , GROUP_CONCAT(id ORDER BY id)
   , GROUP_CONCAT(name ORDER BY id)
   , field
FROM theTable
WHERE field IS NOT NULL
GROUP BY field
UNION 
SELECT id, id, name, field
FROM theTable
WHERE field IS NULL
;

*聚合函数会忽略NULL值,因此从技术上讲,如果id或name包含NULL,则列表将变得未对齐; 可以使用GROUP_CONCAT(IFNULL(concatenated_value, '[null]') ORDER BY ordering_value)进行补救

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM