I have a table that is of meter readings, the fields are:
id_lecturas int(10) unsigned NOT NULL
fk_contadores int(10) unsigned NULL
fecha_lecturas datetime NULL
valor_lecturas decimal(10,3) NULL
diferencia_lecturas decimal(10,3) NULL
When a record is inserted or modified, all fields except the diferencia_lecturas
are filled in.
The field difference_readings need to be calculated with respect to the previous reading and I think the best option is a trigger.
I have created one like this, but it gives an error:
TRIGGER 'calc_difference_update' AFTER UPDATE ON 'lecturas'
FOR EACH ROW BEGIN
IF NEW.valor_lecturas != OLD.valor_lecturas THEN
UPDATE lecturas
SET NEW.diferencia_lecturas = (NEW.valor_lecturas - IFNULL((
SELECT L2.valor_lecturas
FROM lecturas AS L2
WHERE NEW.fk_contadores = L2.fk_contadores AND L2.fecha_lecturas < NEW.fecha_lecturas AND L2.id_lecturas != NEW.id_lecturas), 0))
WHERE id_lecturas = NEW.id_lecturas;
END IF;
END;
The error is:
You can not specify target table lecturas
for update in FROM clause
Can someone tell me what I'm doing wrong?
Thank you.