Home > Database > Mysql Tutorial > How to Sum Comma-Separated Values in a Column in Legacy MySQL Versions (MySQL 4)?

How to Sum Comma-Separated Values in a Column in Legacy MySQL Versions (MySQL 4)?

Susan Sarandon
Release: 2024-10-30 04:00:02
Original
1112 people have browsed it

How to Sum Comma-Separated Values in a Column in Legacy MySQL Versions (MySQL 4)?

Summing a Comma-Separated Column in MySQL: A Solution for Legacy Versions

In MySQL version 4, handling comma-separated numeric columns presents a challenge when attempting to perform aggregations. However, while modern versions of MySQL offer stored procedures to address such complexities, they are not available in MySQL 4.

Unfortunately, MySQL 4 is an outdated version, and its use is highly discouraged. The latest release in the 4.1 branch was 4.1.25 in 2008, rendering it unsupported and obsolete. Most Linux distributions have discontinued providing MySQL 4. If possible, upgrading to MySQL 5 is strongly recommended.

Nonetheless, if upgrading is not feasible, here is an efficient solution for summing comma-separated decimal columns in MySQL 4:

<code class="mysql">DELIMITER //
CREATE FUNCTION SUM_OF_LIST(s TEXT)
RETURNS DOUBLE
DETERMINISTIC
NO SQL
BEGIN
DECLARE res DOUBLE DEFAULT 0;
WHILE INSTR(s, ",") > 0 DO
SET res = res + SUBSTRING_INDEX(s, ",", 1);
SET s = MID(s, INSTR(s, ",") + 1);
END WHILE;
RETURN res + s;
END //
DELIMITER ;</code>
Copy after login

Usage Example:

<code class="mysql">mysql> SELECT SUM_OF_LIST("5,2.1") AS Result;
+--------+
| Result |
+--------+
|    7.1 |
+--------+</code>
Copy after login

The above is the detailed content of How to Sum Comma-Separated Values in a Column in Legacy MySQL Versions (MySQL 4)?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template