DELIMITER $$
CREATE FUNCTION remove_items(orig_list VARCHAR(255), remove_list VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE remove_item VARCHAR(255);
DECLARE final_list VARCHAR(255) DEFAULT '';
SET orig_list = CONCAT(',', orig_list, ',');
WHILE i <= LENGTH(remove_list) - LENGTH(REPLACE(remove_list, ',', '')) + 1 DO
SET remove_item = SUBSTRING_INDEX(SUBSTRING_INDEX(remove_list, ',', i), ',', -1);
SET orig_list = REPLACE(orig_list, CONCAT(',', remove_item, ','), ',');
SET i = i + 1;
END WHILE;
SET final_list = TRIM(BOTH ',' FROM orig_list);
RETURN final_list;
END$$
DELIMITER ;
你可以像这样调用这个函数:
SELECT remove_items('111,222,333', '222'); -- 返回 '111,333'
SELECT remove_items('111,222,333', '222,333,444'); -- 返回 '111'
CREATE FUNCTION remove_items(orig_list VARCHAR(255), remove_list VARCHAR(255))
RETURNS VARCHAR(255)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE remove_item VARCHAR(255);
DECLARE final_list VARCHAR(255) DEFAULT '';
SET orig_list = CONCAT(',', orig_list, ',');
WHILE i <= LENGTH(remove_list) - LENGTH(REPLACE(remove_list, ',', '')) + 1 DO
SET remove_item = SUBSTRING_INDEX(SUBSTRING_INDEX(remove_list, ',', i), ',', -1);
SET orig_list = REPLACE(orig_list, CONCAT(',', remove_item, ','), ',');
SET i = i + 1;
END WHILE;
SET final_list = TRIM(BOTH ',' FROM orig_list);
RETURN final_list;
END$$
DELIMITER ;
你可以像这样调用这个函数:
SELECT remove_items('111,222,333', '222'); -- 返回 '111,333'
SELECT remove_items('111,222,333', '222,333,444'); -- 返回 '111'