如何解决输入数据时的“ MYSQL触发器更新”字段
我有一个名为 procurement 的MYSQL表,其以下各列...
| id | province | sample_result | image | status |
| 1 | prov_1 | 3 | url | Complete |
| 2 | prov_2 | 12 | NULL | |
| 3 | prov_3 | 45 | NULL | |
| 4 | prov_4 | | url | |
我想创建一个TRIGGER,当 both 和sample_result和image列都更新且不再为NULL时,将“ status”列更新为“ Complete”。如果任何一个为NULL,则不需要更新。
解决方法
您可以设置NEW。之前的触发器中的值,因为mysql复制了OLD。新值。获得新之前的价值。更新后的值,然后测试NEW。值很安全
drop table if exists t;
create table t
( id int,province varchar(10),sample_result int,image varchar(10),status varchar(10));
insert into t values
( 1,'prov_1',3,'url','Complete'),( 2,'prov_2',12,NULL,null ),( 3,'prov_3',45,( 4,'prov_4',null,null );
drop trigger if exists t;
delimiter $$
create trigger t before update on t
for each row
begin
if new.sample_result is not null and new.image is not null then
set new.status = 'Complete';
end if ;
end $$
delimiter ;
update t set sample_result = 2 where id = 2;
update t set sample_result = 1 where id = 4;
update t set image = 'url' where id = 3;
select * from t;
+------+----------+---------------+-------+----------+
| id | province | sample_result | image | status |
+------+----------+---------------+-------+----------+
| 1 | prov_1 | 3 | url | Complete |
| 2 | prov_2 | 2 | NULL | NULL |
| 3 | prov_3 | 45 | url | Complete |
| 4 | prov_4 | 1 | url | Complete |
+------+----------+---------------+-------+----------+
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。