'WHERE' condition in an UPDATE TRIGGER giving syntax error :mysql version 5.7
'WHERE' condition in an UPDATE TRIGGER giving syntax error :mysql version 5.7
我正在使用 mysql 数据库(版本 5.7)。
我使用以下 CREATE 命令创建了一个 table:
CREATE TABLE `attendance` (
`id` varchar(11) NOT NULL,
`hash` char(8) NOT NULL,
`time_in` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`time_out` datetime DEFAULT NULL,
`time_spent` time DEFAULT NULL,
`purpose` char(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我有一个带有以下查询的触发器:
DELIMITER $$
CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
SET NEW.time_spent=TIMEDIFF(NEW.time_out,OLD.time_in) WHERE OLD.time_spent IS NULL;
END$$
DELIMITER ;
但是mysql给出了以下错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE OLD.time_spent IS NULL; END' at line 1
(where 条件确保只更新当天的记录)
我该如何编写查询?
您不能在触发器中使用带有 SET
的 WHERE
子句。使用 IF
代替:
DELIMITER $$
CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
IF OLD.time_spent IS NULL THEN
SET NEW.time_spent = TIMEDIFF(NEW.time_out, OLD.time_in);
END IF;
END$$
DELIMITER ;
我正在使用 mysql 数据库(版本 5.7)。
我使用以下 CREATE 命令创建了一个 table:
CREATE TABLE `attendance` (
`id` varchar(11) NOT NULL,
`hash` char(8) NOT NULL,
`time_in` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`time_out` datetime DEFAULT NULL,
`time_spent` time DEFAULT NULL,
`purpose` char(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
我有一个带有以下查询的触发器:
DELIMITER $$
CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
SET NEW.time_spent=TIMEDIFF(NEW.time_out,OLD.time_in) WHERE OLD.time_spent IS NULL;
END$$
DELIMITER ;
但是mysql给出了以下错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE OLD.time_spent IS NULL; END' at line 1
(where 条件确保只更新当天的记录)
我该如何编写查询?
您不能在触发器中使用带有 SET
的 WHERE
子句。使用 IF
代替:
DELIMITER $$
CREATE TRIGGER test_trigger
BEFORE UPDATE ON attendance
FOR EACH ROW
BEGIN
IF OLD.time_spent IS NULL THEN
SET NEW.time_spent = TIMEDIFF(NEW.time_out, OLD.time_in);
END IF;
END$$
DELIMITER ;