我有两张桌子,圆桌和活动。一轮有很多赛事。
create table round (
round_id INTEGER AUTO_INCREMENT NOT NULL,
round_start_date DATETIME NOT NULL,
round_end_date DATETIME NOT NULL,
CONSTRAINT round_pk PRIMARY KEY (round_id)
);
create table event (
event_id INTEGER AUTO_INCREMENT NOT NULL,
round_id INTEGER NOT NULL,
event_date DATETIME NOT NULL,
CONSTRAINT event_pk PRIMARY KEY (event_id),
CONSTRAINT round_fk FOREIGN KEY (round_id) REFERENCES round (round_id),
);
当一行被插入到事件表中时,我想使用触发器将新插入的行的event_date字段与圆桌中相应条目中的round_start_date和round_end_date字段进行比较。如果event_date早于round_start_date,则应使用新的event_date更新round_start_date。如果event_date在round_end_date之后,则应使用新的event_date更新round_end_date。
这是我的触发器。它不起作用,我不明白为什么。我无法在网络上的任何地方找到其他人试图在触发器中使用日期时间类型的内容,因此我没有参考框架来解决我的错误。
create trigger update_round_date
after insert on event for each row
begin
declare curSdate datetime;
declare curEdate datetime;
set curSdate = (select round_start_date from round where round_id = NEW.round_id);
set curEdate = (select round_end_date from round where round_id = NEW.round_id);
if (NEW.event_date < curSdate) then
update round set round_start_date = NEW.event_date where round_id = NEW.round_id;
else if (NEW.event_date > curEdate) then
update round set round_end_date = NEW.event_date where round_id = NEW.round_id;
end if;
end;
编辑:我根本无法创建触发器。 phpMyAdmin给了我这个错误: “#1064 - 您的SQL语法出错;请查看与您的MySQL服务器版本对应的手册,以便在第4行附近使用正确的语法”
编辑2:更新了分隔符集
DELIMITER $$
create trigger update_round_date
after insert on event for each row
begin
declare curSdate datetime;
declare curEdate datetime;
set curSdate = (select round_start_date from round where round_id = NEW.round_id);
set curEdate = (select round_end_date from round where round_id = NEW.round_id);
if (NEW.event_date < curSdate) then
update round set round_start_date = NEW.event_date where round_id = NEW.round_id;
else if (NEW.event_date > curEdate) then
update round set round_end_date = NEW.event_date where round_id = NEW.round_id;
end if;
end$$
这将返回错误:“#1064 - 您的SQL语法出错;请查看与您的MySQL服务器版本对应的手册,以便在第13行附近使用正确的语法”
答案 0 :(得分:1)
phpmyadmin中的分隔符可能存在问题,请尝试使用此触发器 -
CREATE TRIGGER trigger1
AFTER INSERT
ON event
FOR EACH ROW
UPDATE
round
SET
round_start_date =
IF(NEW.event_date < round_start_date, NEW.event_date, round_start_date),
round_end_date =
IF(NEW.event_date > round_end_date, NEW.event_date, round_end_date)
WHERE
round_id = NEW.round_id;
答案 1 :(得分:1)
MySQL可能会在第一个';'处停止,将您的命令解释为:
create trigger update_round_date
after insert on event for each row
begin
declare curSdate datetime;
您必须先将分隔符设置为其他内容,然后使用该分隔符终止create trigger命令(并将分隔符放回最后):
delimiter ^
create trigger update_round_date
after insert on event for each row
begin
...
end;
^
delimiter ;
我相信end
之后的最后一个分号可能是必要的。