我正在寻找一个功能,它会占用超过X天的行并将其放入存档表... 正在考虑制作功能,以便更容易执行...类似
CREATE TABLE archive_NUMBER_OF_WEEK (...);
INSERT INTO archive_NUMBER_OF_WEEK SELECT * FROM content WHERE DATE < X days;
DELETE * FROM content WHERE DATE < X days
如果我自己写的话会发帖:)
答案 0 :(得分:1)
如果你想用一个动态后缀命名归档表(就像我认为你的示例中暗示了NUMBER_OF_WEEK),那么我建议在bash / perl / python中编写一个脚本来执行此操作,而不是使用MySQL存储例程。
此外,如果您使用的是MySQL 5.1,您可能需要考虑按日期对内容表进行分区,以便在归档后轻松删除旧分区。
答案 1 :(得分:0)
使用触发器代替。它们就是为了这些。
答案 2 :(得分:0)
好的,我终极写了:) 我花了一段时间,但现在是:
DELIMITER $$
DROP PROCEDURE IF EXISTS `procedure`.`rotate_events_pro`$$
CREATE DEFINER=`confiq`@`%` PROCEDURE `rotate_events_pro`(p_threshold_rotate_row int,p_days_to_keep int,OUT p_message VARCHAR(200))
BEGIN
DECLARE v_id_to_move INT;
#lets take ID that we need to move
#we can't use variables in LIMIT, how smart MySQL!
SET @v_sql = CONCAT('SELECT max(id)
INTO @v_id_to_move
FROM events
WHERE event_created < DATE_ADD(CURDATE(), INTERVAL - ',p_days_to_keep,' DAY) OR
id < (SELECT min(id) FROM (SELECT id FROM events ORDER BY id DESC LIMIT ?) as id)');
PREPARE stmt1 FROM @v_sql;
SET @param1 = p_threshold_rotate_row;
EXECUTE stmt1 USING @param1;
DEALLOCATE PREPARE stmt1;
#we have IDs that need to to be moved to arhive
IF @v_id_to_move > 0 THEN
START TRANSACTION;
INSERT INTO archived_events SELECT * FROM events WHERE id < @v_id_to_move;
INSERT INTO archived_eventsinfo SELECT * FROM eventsinfo WHERE event_id < @v_id_to_move;
DELETE FROM events WHERE id < @v_id_to_move;
DELETE FROM eventsinfo WHERE event_id < @v_id_to_move;
COMMIT;
SET p_message = CONCAT('moved all events that id is < ',@v_id_to_move);
ELSE
SET p_message = 'Nothing to move';
END IF;
END$$
DELIMITER ;
随意反馈或编辑以供自己使用:)