gpt4 book ai didi

MySQL存储过程选择检查插入

转载 作者:行者123 更新时间:2023-11-29 12:37:01 26 4
gpt4 key购买 nike

所以我尝试在 MySQL 5.5 版本中创建一个存储过程。我不确定哪里出了问题,但我想要完成的是。

从表 A 中获取超过 7 天的记录。然后插入到Table-B中,但是我需要检查它是否存在于B表中。如果存在则跳过,否则插入。

这是我的代码:

DROP PROCEDURE IF EXISTS `move_record`;
DELIMITER //
CREATE PROCEDURE `move_record`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE dt DATETIME;
DECLARE uid,value BIGINT(20);
DECLARE category VARCHAR(30);
DECLARE data,comments VARCHAR(255);
DECLARE cancel TINYINT(1) DEFAULT NULL;

DECLARE curs CURSOR FOR SELECT `datetime`,user_id,category,data,comments,cancel FROM `record` WHERE `datetime` < DATE_SUB(CURDATE(), INTERVAL 7 DAY);

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN curs;

myloop: LOOP
FETCH NEXT FROM curs INTO dt,uid,category,data,comments,cancel;
IF done THEN
LEAVE myloop;
END IF;

IF NOT EXISTS (SELECT * FROM `record_arc`
WHERE record_arc.`datetime` = dt
AND record.user_id = uid )
INSERT INTO `record_arc` (`datetime`,user_id,category,data,comments,cancel) VALUES (dt,uid,category,data,comments,cancel);

END IF;
END LOOP myloop;

CLOSE curs;
DEALLOCATE curs;
END//
DELIMITER ;

最佳答案

也许你可以在没有循环的情况下做到这一点。

INSERT INTO `record_arc`(
`datetime`,
user_id,
category,
data,
comments,
cancel
)
SELECT
`datetime`,
user_id,
category,
data,
comments,
cancel
FROM `record` r
WHERE
`datetime` < DATE_SUB(CURDATE(), INTERVAL 7 DAY)
AND NOT EXISTS(
SELECT 1
FROM `record_arc` r2
WHERE
r2.`datetime` = r.`datetime`
AND r2.user_id = r.user_id
)

关于MySQL存储过程选择检查插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26622957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com