Trigger with MySQL query
What I need to do is the following, when a record is entered into the orders table a trigger is performed that performs the following query:
SELECT timestampdiff(MINUTE, fechaDeSolicitud, now()) <= 120 FROM pedidos
WHERE idPedido= (aqui iria el id del pedido que ingreso como registro)
But I need it to repeat until the result of this query of 0
(will return 1 If 120 minutes have not yet passed or 0 otherwise)
Any idea how I can do it like this other than with a trigger? thank you very much.
4 answers
I would recommend you to do an event from time to time, there are options to refresh automatically in javascript or use a button to refresh manually. and call a function that returns the answer of 0 or 1.
CREATE DEFINER=`root`@`127.0.0.1` FUNCTION `menor_a_120`(fechaDeSolicitud datetime) RETURNS int(11)
BEGIN
DECLARE valor INT;
SET @diferencia_minutos=(SELECT timestampdiff(MINUTE, fechaDeSolicitud, now()) );
IF (@diferencia_minutos<=120) THEN
SET valor=0;
ELSE
SET valor=1;
END IF;
RETURN valor;
END
And then in your javascript you send a query and you see that's what returns you, so you don't load as much work into the database.
You can try something like this, although I warn that I have not tried it:
CREATE TRIGGER trigger_pedidos AFTER INSERT ON pedidos
BEGIN
DECLARE v1 INT DEFAULT 1;
WHILE v1 > 0 DO
SET v1 = (SELECT timestampdiff(MINUTE, fechaDeSolicitud, now()) <= 120 FROM pedidos
WHERE idPedido= (aqui iria el id del pedido que ingreso como registro))
END WHILE;
END;
As I understand the query could be 120 minutes waiting for the condition. The best thing if you're using linux is to make a process that does that job and runs for example every 1 minute, you enroll it in the crontab
I don't see much point in creating a trigger that executes a query, unless the result of that query is saved to a temporary table or a variable that you can use elsewhere in your project.
If you want to do something like this, I can think of this:
-- Opcion 1: Almacenar el resultado en una variable
delimiter $$
create trigger tr_pedidos_ai
after insert on pedidos
for each row
begin
SELECT timestampdiff(MINUTE, fechaDeSolicitud, now()) <= 120
INTO @ts_diff
FROM pedidos
WHERE idPedido=new.id_pedido;
end $$
delimiter ;
In some other part of your application, you can run this query:
select @ts_diff;
Which will return the value you are interested in.
Now, you can also create a function that executes the query and return what you want, and call that function when you need it:
delimiter $$
create function ts_diff(id int) returns int
begin
declare diff int;
select timestampdiff(MINUTE, fechaDeSolicitud, now()) <= 120
into diff
from pedidos
where idPedido = id;
return coalesce(diff, 0);
end $$
delimiter;
And you can run this function whenever you need it in some other part of your application:
set @idPedido = 1; -- valor de prueba
select ts_diff(@idPedido);