SQL中的时差计算

时间:2018-07-26 14:14:33

标签: mysql triggers

你好,我正在尝试创建一个触发器(或多个触发器),以便计算mysql表中的时间差(我正在使用mysql 5.7.21)。 我的桌子是这样的:

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

关于表的一些解释:用户名列是不言自明的,状态列仅获得3个值中的1个:'active','not active','working'。 具体而言,一个人可以从“活跃”更改为“不活跃” /“工作”,反之亦然,但不能从“不活跃”更改为“工作”或从“工作”更改为“不活跃”。 我要做的是跟踪一个人活跃/工作了多少时间。 现在我的想法是有一个这样的表:

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。当有人切换到``非活跃''时,时间表将获得当前时间作为时间并添加计时工作的开始时间和结束时间之间的差异。触发器显示以下错误:

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

不知道这是怎么回事。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决此问题的方法,尽管它不是我期望的那样。我对表结构进行了如下更改:

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 ;

希望这可以帮助任何与我有相同问题的人!