目前,我有一个每5分钟运行一次的cron作业,并且总是填充:“数据”中的record_id,时间戳和加热状态(1和0)。表
我想创建一个触发器,插入数据'表将捕获第一次出现的加热状态' 1' (加热)并将数据插入到“加热数据”中。 table(record_id_on,timestamp和heating_on,它需要保持休眠状态,直到加热设置为' 0'(加热关闭),然后它应该触发更新到最后一行并插入timestamp_off和heating_off。
DELIMITER //
create TRIGGER heating_data_insert
AFTER INSERT ON nest_stats.data
FOR EACH ROW
BEGIN
DECLARE id_exists Boolean;
select 1
into @id_exists
from nest_stats.data
where record_id= new.record_id
and heating = 1
;
if @id_exists = 1
then
insert nest_stats.heating_data
SET record_id_on= (select max(record_id) from nest_stats.data),
device_serial_number=new.device_serial_number,
user_id=new.user_id,
timestamp_on=new.timestamp,
heating_on=new.heating;
END IF;
select 2
into @id_exists
from nest_stats.data
where record_id= new.record_id
and heating = 0 ;
if @id_exists = 2
then
update nest_stats.heating_data
SET record_id_off= new.record_id,
timestamp_off=new.timestamp,
heating_off=new.heating
where record_id_on =(select max(record_id_on) from nest_stats.data);
END IF;
END;
//
DELIMITER ;
<code>