如何在 MySQL 中对逗号分隔的字符串(包含数字的字符串)求和?


你可创建一个自定义函数,在 MySQL 中对逗号分隔的字符串进行求和。让我们先创建一个表。这里,我们有一个 varchar 列,其中我们会以字符串形式添加数字 −

mysql> create table DemoTable
   -> (
   -> ListOfValues varchar(50)
   -> );
Query OK, 0 rows affected (0.56 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('20,10,40,50,60');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+----------------+
| ListOfValues   |
+----------------+
| 20,10,40,50,60 |
+----------------+
1 row in set (0.00 sec)

下面是创建函数的查询 −

mysql> DELIMITER ??
mysql> create function totalSumInCommaSeparatedString(input varchar(50))
   -> returns int
   -> deterministic
   -> no sql
   -> begin
   -> declare totalSum int default 0;
   -> while instr(input, ",") > 0 do
   -> set totalSum = totalSum + substring_index(input, ",", 1);
   -> set input = mid(input, instr(input, ",") + 1);
   -> end while;
   -> return totalSum + input;
   -> end ??
Query OK, 0 rows affected (0.17 sec)
mysql> DELIMITER ;

让我们检查一下上述函数,在 MySQL 中获得逗号分隔字符串的总和 −

mysql> select totalSumInCommaSeparatedString(ListOfValues) as TotalSum from DemoTable;

这将产生以下输出 −

+----------+
| TotalSum |
+----------+
|      180 |
+----------+
1 row in set (0.00 sec)

更新于: 13-Dec-2019

984 次浏览

启动你的 职业生涯

完成课程可获得认证

立即开始
广告
© . All rights reserved.