gpt4 book ai didi

MySQL触发器删除旧记录并插入新记录

转载 作者:行者123 更新时间:2023-11-30 23:15:42 25 4
gpt4 key购买 nike

我有一个表格如下

Table name: sda_user_eform_data

ack_no Name Description
1 name1 This is name1
2 name2 This is name2
3 name3 This is name3

我有另一个表 sda_user_eform_data_bckup,它与 sda_user_eform_data 具有完全相同的结构。我只想在 sda_user_eform_data 中存储 5 行(最新行),只要 ackno 大于 5,就应将旧值移至第二个(sda_user_eform_data_bckup)表。

为此,我首先将 sda_user_eform_data 表中的所有行复制到 sda_user_eform_data_bckup 表中。然后我创建了以下触发器,其中我检查了 ack_no,如果它大于 5,则删除最旧的 ack_no 并将新值插入到 bckup 表中。

DELIMITER $$
create
trigger 'copy_eform_data' AFTER INSERT
on asdb.sda_user_eform_data
for each row begin
if (select count(s.ack_no) from asdb.sda_user_eform_data s)>5 then
delete from asdb.sda_user_eform_data where old.ack_no=(select min(s.ack_no) from asdb.sda_user_eform_data s);
insert into asdb.sda_user_eform_data_bckup select * from asdb.sda_user_eform_data where ack_no=select max(s.ack_no) from asdb.sda_user_eform_data s;
end$$
DELIMITER ;

我无法找出触发器出错的地方,因为它没有执行。我们非常欢迎任何建议。

提前致谢。

最佳答案

这很可能是因为您的触发器根本不存在。问题就在这里

create
trigger 'copy_eform_data'

带单引号的 copy_eform_data 是一个字符串。

看看这篇文章:When to use single quotes, double quotes, and backticks?

您还应该阅读触发器中的 NEWOLD 关键字。您的触发器可能永远不会匹配一行。

这里

where ack_no=select max(s.ack_no) from asdb.sda_user_eform_data s

您缺少括号。

除此之外,老实说,我并没有真正深入思考你的逻辑,因为我看不出你的整个问题有什么意义。为什么要有重复数据?我猜是出于性能原因?适本地为您的表编制索引,应该没有问题。要获取表中的 5 个最新条目,只需使用

FROM yourTable
ORDER BY when_was_the_entry_created_or_something DESC
LIMIT 5

你可以有这样的列

created timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

在您的 ORDER BY 中使用。您可能需要该列的索引。

关于MySQL触发器删除旧记录并插入新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963694/

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