MySQL触发器在插入具有新的自动增量ID的更新列之前

编程入门 行业动态 更新时间:2024-10-25 10:22:25
本文介绍了MySQL触发器在插入具有新的自动增量ID的更新列之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用国家代码和新的id(这是一个自动递增的值)更新表中的列.

I'd like to update a column in my table with the country code and the new id which is an auto-increment value.

BEGIN SET new.key = concat(new.countryCode,new.id); END

countryCode可以正常工作,但是id始终为空白.我该如何实现这样的目标? id来自autoincrement列.

countryCode works fine, but the id is always blank. How can I achieve something like this? The id comes from an autoincrement column.

我知道它不起作用,因为它是在插入后生成的.那我该怎么做呢?

I know it's not working because it's generated after the insert. So how can I do something like this?

推荐答案

AUTO_INCREMENT列仅在插入之后设置.

如果您需要访问该值,则只能在AFTER INSERT触发器中.但是,您不能在AFTER UPDATE触发器中修改列值...

If you need to access that value, you can only in an AFTER INSERT trigger. However, you cannot modify a column value in an AFTER UPDATE trigger...

此外,您不能以( dev.mysql/doc/refman/5.0/en/stored-program-restrictions.html ):

在存储的函数或触发器中,不允许修改 表格已经被(读取或写入)使用的表格 调用该函数或触发器的语句.

Within a stored function or trigger, it is not permitted to modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

这里唯一合理的解决方案是创建一个存储过程来更新表,调整事务中的相关列以模拟"您的原子插入语句.

Here the only reasonable solution would be to create a stored procedure to update the table, adjusting the relevant columns in a transaction to "emulate" you atomic insert statement.

也就是说,在您的特定情况下,key列是多余的,因为该列只是同一行中其他两个列的串联.

That being said, in your particular case, the key column is redundant as that column is just the concatenation of two other columns of the same row.

给出它的名字,您不是在寻找一种创建复合键的方法吗?像这样的东西:

Given its name, aren't you looking for a way to create a compound key instead? Something like that:

ALTER TABLE tbl ADD UNIQUE KEY (countryCode, id);

更多推荐

MySQL触发器在插入具有新的自动增量ID的更新列之前

本文发布于:2023-10-15 02:35:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:触发器   增量   MySQL   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!