MySQL 中的 group_concat 能否给空字段添加分隔符?
我们可以使用 replace() 和 group_concat() 来达到这一目的。在此,对于空字段,我们将其显示为分隔符。我们首先创建一个表 -
mysql> create table DemoTable ( Id int, Number varchar(100) ); Query OK, 0 rows affected (2.03 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable values(10,'456'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(11,'345'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(10,''); Query OK, 1 row affected (0.63 sec) mysql> insert into DemoTable values(10,'278'); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable values(10,''); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable values(10,'789'); Query OK, 1 row affected (0.47 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+------+--------+ | Id | Number | +------+--------+ | 10 | 456 | | 11 | 345 | | 10 | | | 10 | 278 | | 10 | | | 10 | 789 | +------+--------+ 6 rows in set (0.00 sec)
以下是给空字段添加分隔符的查询 -
mysql> select Id,replace(group_concat(Number),',,',',') from DemoTable group by Id;
这将产生以下输出 -
+------+----------------------------------------+ | Id | replace(group_concat(Number),',,',',') | +------+----------------------------------------+ | 10 | 456,278,789 | | 11 | 345 | +------+----------------------------------------+ 2 rows in set (0.00 sec)
广告