DROP TABLE IF EXISTS `autosearch_viewed`;

CREATE TABLE `autosearch_viewed` (
    `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 autoSearchViewed;

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

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

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

OPEN currentFilter;

ALTER TABLE `autosearch_results` DROP `viewed`;

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

DELIMITER ;

CALL autoSearchViewed();
DROP PROCEDURE IF EXISTS autoSearchViewed;