目标效果
原字符串值:101,102,103,102
处理后的值:101,102,103
创建一个函数
CREATE FUNCTION remove_duplicate_values(val VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE result VARCHAR(255) DEFAULT '';
DECLARE arr VARCHAR(255) DEFAULT '';
DECLARE i INT DEFAULT 0;
DECLARE val_len INT DEFAULT 0;
DECLARE sub_val VARCHAR(255);
SET arr = replace(val, ',', ',');
SET val_len = CHAR_LENGTH(arr);
WHILE i < val_len DO
SET sub_val = SUBSTRING_INDEX(SUBSTRING_INDEX(arr, ',', i + 1), ',', -1);
IF NOT FIND_IN_SET(sub_val, result) THEN
SET result = CONCAT(result, sub_val, ',');
END IF;
SET i = i + 1;
END WHILE;
SET result = TRIM(TRAILING ',' FROM result);
RETURN result;
END;
调用函数测试
SELECT remove_duplicate_values(‘字符串值’);
结合SQL
Update table_name SET Field_Name=remove_duplicate_values(Field_Name) WHERE …