DROP TABLE IF EXISTS `autosearch_favoured`;

CREATE TABLE `autosearch_favoured` (
    `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 autoSearchFavoured;

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

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

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

OPEN currentFilter;

ALTER TABLE `autosearch_results` DROP `favoured`;

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

DELIMITER ;

CALL autoSearchFavoured();
DROP PROCEDURE IF EXISTS autoSearchFavoured;