我有一个每周出席的Mysql表..
CREATE TABLE IF NOT EXISTS `students_attendance` (
`student_id` SMALLINT(5) UNSIGNED ZEROFILL NOT NULL,
`month` TINYINT UNSIGNED NOT NULL,
`w1` ENUM ('Absent', 'Present', 'Leave') NULL,
`w2` ENUM ('Absent', 'Present', 'Leave') NULL,
`w3` ENUM ('Absent', 'Present', 'Leave') NULL,
`w4` ENUM ('Absent', 'Present', 'Leave') NULL,
`w5` ENUM ('Absent', 'Present', 'Leave') NULL,
`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`student_id`, `month`)
) ENGINE=InnoDB;
我使用触发器每个月自动插入新行
DELIMITER $$
CREATE TRIGGER update_students_attendance
BEFORE UPDATE ON `students_attendance` FOR EACH ROW
begin
DECLARE new_month TINYINT;
SET new_month = (SELECT month FROM students_attendance WHERE student_id = NEW.student_id AND month = NEW.month);
IF new_month is NULL OR new_month = ''
THEN
INSERT INTO students_attendance (student_id, month) VALUES (NEW.student_id, NEW.month);
END IF;
END;
$$
DELIMITER ;
但是当我使用下面的update语句时,它不会插入任何行......
UPDATE students_attendance set `w1` = 'Absent' where `student_id` = '1' and `month` = '1'
谁能帮助我?
答案 0 :(得分:-1)
DELIMITER $$
CREATE TRIGGER update_students_attendance
BEFORE UPDATE ON `students_attendance` FOR EACH ROW
begin
DECLARE new_month TINYINT;
(SELECT month into new_month FROM students_attendance WHERE student_id = NEW.student_id AND month = NEW.month);
IF new_month is NULL OR new_month = ''
THEN
INSERT INTO students_attendance (student_id, month) VALUES (NEW.student_id, NEW.month);
END IF;
END;
$$
DELIMITER ;
尝试以上代码。
答案 1 :(得分:-1)
请检查下面提到的触发器。
DELIMITER $$
CREATE TRIGGER update_students_attendance
BEFORE UPDATE ON `students_attendance` FOR EACH ROW
begin
DECLARE new_month TINYINT DEFAULT 0;
SELECT month into new_month FROM students_attendance WHERE student_id = NEW.student_id AND month = NEW.month;
IF new_month is NULL OR new_month < 1 THEN
INSERT INTO students_attendance (student_id, month) VALUES (NEW.student_id, NEW.month);
END IF;
END;
$$
DELIMITER ;
答案 2 :(得分:-2)
UPDATE students_attendance SET w1='Absent' WHERE student_id='1' AND month='1'