您可以做的是在 MySQL 中创建一个用户定义的函数,该函数循环,将字符串中的每个重复数字一次替换一个值(例如0000 -> 000 -> 00 -> 0
),直到该数字唯一:
DELIMITER $$
CREATE FUNCTION removeDuplicates (str VARCHAR(255)) RETURNS VARCHAR(255)
BEGIN
DECLARE prevVal VARCHAR(255);
DECLARE curVal VARCHAR(255);
SET curVal = str;
REPEAT
SET prevVal = curVal;
SET curVal = REPLACE(REPLACE(prevVal, '11', '1'), '00', '0');
UNTIL prevVal = curVal
END REPEAT;
RETURN curVal;
END$$
DELIMITER ;
然后,您可以在查询中的任何位置使用此功能。例如:
SELECT removeDuplicates(your_column) FROM your_table
示例输出:
SELECT removeDuplicates('0101111101010000');
---> 010101010
SELECT removeDuplicates('011100000111100101010');
---> 01010101010
SELECT removeDuplicates('111010001011101110100010101');
---> 10101010101010101
SELECT removeDuplicates('111111111111111111111');
---> 1
SELECT removeDuplicates('000000000000000000000');
---> 0
SELECT removeDuplicates('11');
---> 1
SELECT removeDuplicates('00');
---> 0
SELECT removeDuplicates('1');
---> 1
SELECT removeDuplicates('0');
---> 0