随手记:MySQL根据指定字符串拆分求和

因业务需求,需要将一对多的数据合并到一个字段中,用位运算的方式(2的n次方,再求和)来经行数据存储。于是用了 GROUP_CONCAT 函数,将多个数据按默认字符 “,” 进行字符串拼接。然而,想要经行将数据相加的时候,发现MySQL中没有Java中常用的split函数。于是,本人写了一个拆分求和的函数,以满足业务需求。

DROP FUNCTION IF EXISTS split_sum;
CREATE FUNCTION split_sum (str VARCHAR(200)) RETURNS INT(20)
DETERMINISTIC
BEGIN
	DECLARE max_size INT(11);
	DECLARE i INT(11);
	DECLARE sum INT(20);
	SET max_size = LENGTH(str) - LENGTH(REPLACE(str, ',', '')) + 1;
	SET i = 0;
	SET sum = 0;
	WHILE i < max_size DO
		SET i = i + 1;
		SET sum = sum + SUBSTRING_INDEX(SUBSTRING_INDEX(str, ',', i),',',-1);
	END	WHILE;
	RETURN sum;
END;

简单测试

SELECT split_sum('1,2,5,7,15');

顺便附上GROUP_CONCAT运用的一个小demo

SELECT
	a.id,
	split_sum(GROUP_CONCAT(CASE	WHEN a.type = 1 THEN POWER(2, a.label_id) ELSE 0 END)) market_labels,
	split_sum(GROUP_CONCAT(CASE WHEN a.type = 2 THEN POWER(2, a.label_id) ELSE 0 END)) tort_labels
FROM
	(
		SELECT
			1 AS id,
			1 AS label_id,
			1 AS type
		UNION
			SELECT
				1 AS id,
				1 AS label_id,
				2 AS type
			UNION
				SELECT
					1 AS id,
					3 AS label_id,
					1 AS type
				UNION
					SELECT
						1 AS id,
						7 AS label_id,
						2 AS type
	) a
GROUP BY
	a.id;

如果有什么疑问或者更好的方法,欢迎留言交流。^ _ ^

你可能感兴趣的:(mysql)