DROP TABLE IF EXISTS `autosearch_ignored`;

CREATE TABLE `autosearch_ignored` (
    `filter_id` INT(11) UNSIGNED NOT NULL COMMENT 'ИД фильтра' ,
    `object_id` INT(11) UNSIGNED NOT NULL COMMENT 'ИД объекта'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci COMMENT='Таблица игнорируемых объектов в автопоиске';

DROP PROCEDURE IF EXISTS autoSearchIgnored;

DELIMITER //
CREATE PROCEDURE autoSearchIgnored()
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE indx INTEGER DEFAULT 0;
    DECLARE filter_id VARCHAR(4000);
    DECLARE ignored VARCHAR(4000);

    DECLARE currentFilter CURSOR FOR
        SELECT `autosearch_results`.`filter_id` AS 'filter_id',
            JSON_EXTRACT(REPLACE(`autosearch_results`.`ignored`, '&quot;', ''), '$')
        FROM `autosearch_results`
        WHERE `autosearch_results`.`ignored` != '' AND
            `autosearch_results`.`ignored` IS NOT NULL AND
            `autosearch_results`.`ignored` != 'null' AND
            `autosearch_results`.`ignored` NOT LIKE '[]';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

OPEN currentFilter;

ALTER TABLE `autosearch_results` DROP `ignored`;

getIgnored: LOOP
        FETCH currentFilter INTO filter_id, ignored;
        IF finished = 1 THEN LEAVE getIgnored;
END IF;
        WHILE indx < JSON_LENGTH(ignored) DO
SELECT `filter_id`, JSON_EXTRACT(ignored, CONCAT('$[', indx, ']')) AS `object_id`;
INSERT INTO `autosearch_ignored` (`filter_id`, `object_id`) VALUES (`filter_id`, JSON_EXTRACT(ignored, CONCAT('$[', indx, ']')));
SET indx = indx + 1;
END WHILE;
        SET indx = 0;
END LOOP getIgnored;
CLOSE currentFilter;
END; //

DELIMITER ;

CALL autoSearchIgnored();
DROP PROCEDURE IF EXISTS autoSearchIgnored;