如何在MySQL中求和逗号分隔的字符串(带有数字的字符串)?

如何在MySQL中求和逗号分隔的字符串(带有数字的字符串)?

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

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

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

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)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程