我正在尝试强制执行独特的约束。我有两个表,有一个公共列 puuid。两者的价值都是独一无二的。如果用户尝试将 puuid 插入 table1 并且该 puuid 已存在于 table2 中,则应该阻止我这样做。我无法让它工作。这是我的查询:
create table if not exists table1
(puuid varchar(50) not null unique)
create table if not exists table2
(puuid varchar(50) not null unique)
delimiter $$
create trigger temp_trigger
before INSERT
on table2 t2 for each ROW
BEGIN
declare c int,
select count(*) into c from table1 t1 where t1.puuid = NEW.puuid
if (c > 0) THEN
-- abort insert because puuid cannot be null
set NEW.puuid = NULL;
end if;
END$$
delimiter;
insert into table1 (puuid)
values ('22')
insert into table2 (puuid)
values ('22')
Run Code Online (Sandbox Code Playgroud)
仍然插入成功。我究竟做错了什么?
您的代码有一些错误,更正了代码,使之符合您的需要
但更好的方法是使用SIGNAL 语句
查看第二个触发器
Run Code Online (Sandbox Code Playgroud)create table if not exists table1 (puuid varchar(50) not null unique); create table if not exists table2 (puuid varchar(50) not null unique); create table if not exists table3 (puuid varchar(50) not null unique)
Run Code Online (Sandbox Code Playgroud)create trigger temp_trigger before INSERT on table2 for each ROW BEGIN declare c int; select count(*) into c from table1 t1 where t1.puuid = NEW.puuid; if (c > 0) THEN -- abort insert because puuid cannot be null set NEW.puuid = NULL; end if; END;
Run Code Online (Sandbox Code Playgroud)insert into table1 (puuid) values ('22');
Run Code Online (Sandbox Code Playgroud)insert into table2 (puuid) values ('22')列“puuid”不能为空
Run Code Online (Sandbox Code Playgroud)create trigger temp_trigger2 before INSERT on table3 for each ROW BEGIN declare c int; select count(*) into c from table1 t1 where t1.puuid = NEW.puuid; if (c > 0) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'id already exists'; end if; END;
Run Code Online (Sandbox Code Playgroud)insert into table3 (puuid) values ('22')id已经存在
Run Code Online (Sandbox Code Playgroud)SELECT * FROM table1;| 普乌伊德 | | :----| | 22 | 22
Run Code Online (Sandbox Code Playgroud)SELECT * FROM table2;| 普乌伊德 | | :----|
Run Code Online (Sandbox Code Playgroud)SELECT * FROM table3;| 普乌伊德 | | :----|
db<>在这里摆弄