MySQL实现自动使用uuid作为主键以及解决不能调用触发器的一点思路

时间:2022-08-05 12:16:26

这里使用触发程序实现此功能.

触发程序语法如下:

Create trigger <tri_name>

{before|after}

{insert|update|delete}

On <tab_name>

For each row

<触发程序SQL语句>

核心代码:

 use t14test
show tables
drop table if exists uuidTest
create table uuidTest(
testId VARCHAR() not NULL DEFAULT '',
testData VARCHAR(),
PRIMARY KEY(`testId`)
)
/*创建触发器*/
/*
* terminal创建存储过程需要定义分隔符
* delimiter //
* */
create trigger tri_auto_uuid
before insert
on uuidTest
for each ROW
BEGIN
if new.testId = '' THEN set new.testId = (select uuid());
end if;
END
/*删除触发器*/
drop trigger if exists tri_auto_uuid
/*插入数据*/
insert into uuidTest(testData)VALUES('一条数据')
select * from uuidTest

运行了三次插入操作,结果如下:

MySQL实现自动使用uuid作为主键以及解决不能调用触发器的一点思路

使用触发器可实现uuid作为主键.

有问题的代码:

 create trigger tri_auto_uuid
after insert
on uuidTest
for each ROW
update uuidTest set testId=((select uuid()))

如果这样定义触发程序,看似没问题,也能添加成功,但是录入数据会报错.

Can't update table 'tb_user' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

网上说为了避免递归触发,update一条数据后不能触发对该数据进行除了Set之外的更新操作.否则就会报错.

可是我这个触发器是after insert 而且是Set 操作,为什么会有问题呢?

这里存在某种原因,可能和递归触发有关系.暂且不去管他底层是如何运作的.只需要改变一下思路,把after insert 改成 before insert 就行了.