sql中的时差计算

xpszyzbs  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(337)

你好,我正在尝试创建一个触发器(或更多)来计算mysql表中的时间差(我使用的是MySQL5.7.21)。我的table是这样的:

CREATE TABLE people(
username VARCHAR(255) NOT NULL,
state VARCHAR(255) NOT NULL DEFAULT 'not active',
PRIMARY KEY(username)
);

关于该表的一些说明:username列是自解释的,state列只得到3个值中的1个:“active”、“not active”、“working”。具体来说,一个人可以从“活跃”变为“不活跃”/“工作”,反之亦然,但不能从“不活跃”变为“工作”,也不能从“工作”变为“不活跃”。我想做的是记录一个人活跃/工作了多长时间。现在我的想法是有一张这样的table:

Create table Time(
username VARCHAR(255) NOT NULL,
timestarted TIME,
timeended TIME,
timeworking TIME,
FOREIGN KEY (username) REFERENCES people(username)
);

我的第一个猜测是使用 CURRENT_TIME() 函数使用触发器跟踪状态。我所做的是:

Delimiter $$

CREATE TRIGGER time_calculation
BEFORE Update 
ON people 
FOR EACH ROW BEGIN
DECLARE @times time;
DECLARE @timee time;
DECLARE @timet time;
IF OLD.state = 'not active' THEN
UPDATE Time SET timestart = CURRENT_TIME()  WHERE username = new.username;
END IF;
IF NEW.state = 'not active' THEN
set @times = (select timestarted from time where username = new.username);
set @timee = (select timeended from time where username = new.username);
set @timet = (select timeworking from time where username = new.username);
    UPDATE Time SET timeend = CURRENT_TIME(),timeworking = (TIMEDIFF(times,timee)+timet) WHERE username = new.username;
    END IF;
END$$

根据这个触发器。每次有人从“非活动”切换到“活动”时,时间表将获取该开关的当前时间作为timestart。当有人切换到“非活动”时,时间表将获取当前时间作为timeend,并将timestart和timeend之间的差异添加到timeworking中。触发器显示以下错误:

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 'DECLARE @times time;
DECLARE @timee time;
DECLARE @timet time;
BEGIN
IF OLD.state =' at line 5

不知道怎么了。有什么想法吗?

ctehm74n

ctehm74n1#

好吧,我找到了解决这个问题的方法,虽然它不是我所期望的。我对表格结构做了如下更改:

Create table people (
username VARCHAR(255) NOT NULL,
Primary Key (username)
);

Create table characteristics (
username VARCHAR(255) NOT NULL,
state VARCHAR(25) NOT NULL DEFAULT 'not active',
timestart TIME,
timestop TIME,
timetotal TIME NOT NULL DEFAULT '00:00:00',
FOREIGN KEY(username) REFERENCES people(username)
);

至于获取时差的触发器,如下所示:

Delimiter $$

CREATE TRIGGER time_calculation
BEFORE Update 
ON characteristics 
FOR EACH ROW BEGIN
IF OLD.state = 'not active' && NEW.state != 'not active' THEN
SET NEW.timestart = CURRENT_TIME();
END IF;
IF NEW.state = 'not active' && OLD.state != 'not active' THEN
SET NEW.timestop = CURRENT_TIME();
SET NEW.timetotal = ADDTIME(OLD.timetotal,TIMEDIFF(NEW.timestop, OLD.timestart));
END IF;
END$$ 

Delimiter ;

希望这能帮助任何和我有同样问题的人!

相关问题