DELIMITER $$
CREATE TRIGGER t_insert BEFORE INSERT ON bookmanagement.reader
FOR EACH ROW
BEGIN
IF exists(SELECT * FROM reader WHERE readerId=new.readerId)
UPDATE reader SET sum = sum+1 WHERE readerId=new.readerId;
ELSE
INSERT INTO reader(readerId,Name,sex) VALUES(new.readerId,new.Name,new.sex);
END; $$
DELIMITER ;
在插入数据时判断一下能否已存在,若已存在,就对sum属性加1,不存在就插入数据,这样写有错吗
CREATE TRIGGER t_insert BEFORE INSERT ON bookmanagement.reader
FOR EACH ROW
BEGIN
IF exists(SELECT * FROM reader WHERE readerId=new.readerId)
UPDATE reader SET sum = sum+1 WHERE readerId=new.readerId;
ELSE
INSERT INTO reader(readerId,Name,sex) VALUES(new.readerId,new.Name,new.sex);
END; $$
DELIMITER ;
在插入数据时判断一下能否已存在,若已存在,就对sum属性加1,不存在就插入数据,这样写有错吗
解决方案
40
DELIMITER $$
CREATE TRIGGER t_insert BEFORE INSERT ON bookmanagement.reader
FOR EACH ROW
BEGIN
IF exists(SELECT * FROM reader WHERE readerId=new.readerId) THEN
UPDATE reader SET sum = sum+1 WHERE readerId=new.readerId;
ELSE
INSERT INTO reader(readerId,Name,sex) VALUES(new.readerId,new.Name,new.sex);
end if;
END; $$
DELIMITER ;
CREATE TRIGGER t_insert BEFORE INSERT ON bookmanagement.reader
FOR EACH ROW
BEGIN
IF exists(SELECT * FROM reader WHERE readerId=new.readerId) THEN
UPDATE reader SET sum = sum+1 WHERE readerId=new.readerId;
ELSE
INSERT INTO reader(readerId,Name,sex) VALUES(new.readerId,new.Name,new.sex);
end if;
END; $$
DELIMITER ;