Trigger update multiple field in MySql/MariaDB - mysql

I need to create a single trigger that runs after inserting a row in the table Documenti and makes the 2 updates shown in the following query
UPDATE AllegatoZip AS a
LEFT JOIN Documenti AS d on d.allegato = a.idAllegato
SET a.data_invio_operatore = d.data_invio_doc
WHERE NEW.allegato = a.idAllegato AND NEW.data_invio_doc > a.data_invio_operatore;
UPDATE AllegatoZip AS a SET a.dataInserimento = now()
WHERE NEW.allegato = a.idAllegato;
The trigger I created with just one update works
CREATE TRIGGER AggiornaDataDocumenti AFTER INSERT ON Documenti
FOR EACH ROW UPDATE AllegatoZip a
LEFT JOIN Documenti d on a.idAllegato = d.allegato
SET a.data_invio_operatore = d.data_invio_doc
WHERE NEW.allegato = a.idAllegato AND NEW.data_invio_doc > a.data_invio_operatore
SQL Database model: https://ibb.co/msnvNe
PS. sorry for my English
UPDATE: I SOLVED
DELIMITER $$
CREATE TRIGGER `AggiornaDataDocumenti` AFTER INSERT ON `Documenti` FOR EACH ROW BEGIN
DECLARE docID INT;
SET docID = NEW.allegato;
UPDATE AllegatoZip a
LEFT JOIN Documenti d on a.idAllegato = d.allegato
SET a.data_invio_operatore = d.data_invio_doc
WHERE
docID = a.idAllegato AND d.data_invio_doc > a.data_invio_operatore;
UPDATE AllegatoZip a SET a.dataInserimento = now()
WHERE
docID = a.idAllegato;
END
$$
DELIMITER ;

Related

How to compare two tables SUM and Update another Table With MySql Trigger

compare two tables SUM and Update another Table With MySql Trigger
DELIMITER $$
CREATE TRIGGER change_com_status_on_sales_table AFTER INSERT ON `commision_calculation` // COMMISSION TABLE
FOR EACH ROW
BEGIN
DECLARE totalQnt1, totalQnt2 DOUBLE;
DECLARE sales_id INT;
SET #sales_id=(SELECT sales_info_id
FROM commercial_invoice WHERE ci_no = NEW.ci_no);
SET #totalQnt1=(SELECT sum(cc.quantity) as total_qnt1
FROM commision_calculation cc
LEFT JOIN commercial_invoice ci ON cc.ci_id = ci.id
WHERE cc.comission_type = 'Remex' AND ci.sales_info_id= #sales_id
GROUP BY #sales_id);
SET #totalQnt2=(SELECT SUM(sii.quantity) as total_income
FROM sales_info_item sii WHERE sii.sales_info_id = #sales_id
GROUP BY #sales_id);
IF (#totalQnt2 > #totalQnt1) THEN
UPDATE sales_information
SET ci_status = 'Partial'
WHERE id = #sales_id;
END IF;
IF (#totalQnt2 = #totalQnt1) THEN
UPDATE sales_information
SET ci_status = 'Full'
WHERE id = #sales_id;
END IF;
END; $$
DELIMITER ;
The error in above as mentioned by Jahid Hossain
I get "SQLSTATE[21000]: Cardinality violation: 1242 Subquery returns more than 1 row"

Dynamic name tablе in trigger

There is a trigger that copies columns from one table to another. How do I assign a table name to a dynamic variable #nametable?
Every day the name of the table changes depending on the current date.
USE dbo;
DROP TRIGGER IF EXISTS `update_test`;
GO
DELIMITER |
CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
DECLARE nametable VARCHAR(128);
SET #nametable =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
INSERT INTO `dbo`.`nametable` SET
`TIME_` =NEW.`recorded`,
`P1` = NEW.`value1`
ON DUPLICATE KEY UPDATE
`TIME_` = NEW.`recorded`,
`P1` = NEW.`value1`;
END;
Have error ERROR 1146: Table 'dbo.nametable' doesn't exist
I decided to do so as a temporary solution:
CREATE TRIGGER `update_test` AFTER INSERT ON `hello_send`
FOR EACH ROW
BEGIN
SET #dateNameTableNOW =(DATE_FORMAT(NOW(),"%d%m%Y_v"));
SET #dateNameTableSELECT1 = '06122017_v';
SET #dateNameTableSELECT2 = '07122017_v';
IF(#dateNameTableNOW = #dateNameTableSELECT1) THEN
INSERT INTO dbo.06122017_v SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;
IF(#dateNameTableNOW = #dateNameTableSELECT2) THEN
INSERT INTO dbo.07122017_v SET TIME_=NEW.recorded, P1 = NEW.value1 ON DUPLICATE KEY UPDATE TIME_ = NEW.recorded, P1 = NEW.value1;
END IF;
END;

Update a second table, using trigger

I'm trying to create a simple trigger, but, i can't set the media value on prato if the value comes from #total or #sum.
I've already tested to substitute them for "1" or "1+1", to see if i wasn't even updating correctly or the problem was the operation itself.
DELIMITER $$
CREATE
TRIGGER ratings_prato BEFORE INSERT ON ratings
FOR EACH ROW BEGIN
SET #total = #total + 1;
SET #sum = NEW.stars + #sum;
UPDATE prato p SET p.media = #sum/#total WHERE p.id = 1;
END;
$$
DELIMITER ;
Any ideias?
I've completed mislead the FOR EACH ROW on trigger. I thought, every time it was updated, It would run trough all rows. But, instead of it, it executes for each row it was updated, which, make things possible.
This was the last result of my trigger, inserting on ratings, and updating on food(which was prato)
DELIMITER $$
CREATE
TRIGGER inserting_dishes_rating AFTER INSERT ON ratings
FOR EACH ROW BEGIN
IF(NEW.food_id is not null) THEN
SET #media = (SELECT SUM(stars) FROM ratings WHERE food_id = NEW.food_id) / (SELECT COUNT(*) FROM ratings WHERE food_id = NEW.food_id);
      UPDATE foods f SET f.rate = #media WHERE f.id = NEW.food_id;
    ELSE
  SET #media = (SELECT SUM(stars) FROM ratings WHERE restaurant_id = NEW.restaurant_id) / (SELECT COUNT(*) FROM ratings WHERE restaurant_id = NEW.restaurant_id);  
UPDATE restaurants r SET r.rate = #media WHERE r.id = NEW.restaurant_id;
END IF;
END

MySql Error 1054 when inserting into table that has trigger

I have created a trigger on a table, and when I try to insert data into it I get MySql error "Error Code: 1054 'unknown column license_key in field list'"
The INSERT I try to do is this:
INSERT INTO LOAD_MASTER(license_key, state, total_pageviews, total_visitors, max_visitors, max_pageviews, ip, secret, read_time, url)
VALUES ("order55555hytgtrfderfredfredfredftyu8ikloi98nhygt6", "preparing", 400, 1000, 200, 400, "202,2,35,36", "Hemmeligheden", 120, "http://google.dk");
The Trigger I have created is supposed to check the TABLE LOAD_STATS for the presence of the IP entered in the LOAD_MASTER table, and then based on the results change a value in another table called LICENSE
My trigger is here:
DELIMITER //
CREATE TRIGGER ip_check AFTER INSERT ON LOAD_MASTER FOR EACH ROW
BEGIN
DECLARE MK varchar(50);
DECLARE MIP varchar(15);
DECLARE LID int(6);
SET MK = license_key;
SET MIP = ip;
SET LID = (
SELECT l.license_id
FROM license_keys k, license l
WHERE l.license_id = k.license_id
AND k.license_key = MK
);
IF (SELECT COUNT(DISTICT(master_ip)) FROM LOAD_STATS WHERE master_ip = MIP AND master_key = MK ) > 3 THEN
UPDATE LICENSE
SET STATE = 0
WHERE license_id = LID;
END IF;
END
//
DELIMITER ;
Any help on why I get this error would be much appriciated.
-Dan
In these lines
SET MK = license_key;
SET MIP = ip;
you probably meant to address NEW.license_key and NEW.ip respectively.
IMHO you can make more succinct. Try this
DELIMITER //
CREATE TRIGGER ip_check
AFTER INSERT ON load_master
FOR EACH ROW
BEGIN
IF (SELECT COUNT(DISTICT(master_ip))
FROM load_stats
WHERE master_ip = NEW.ip
AND master_key = NEW.license_key ) > 3 THEN
UPDATE license
SET state = 0
WHERE license_id =
(
SELECT l.license_id
FROM license_keys k JOIN license l
ON l.license_id = k.license_id
AND k.license_key = NEW.license_key
); -- make sure that this subquery returns only ONE record
END IF;
END //
DELIMITER ;
There is some room for improvement rewriting an UPDATE with JOIN instead of using a subquery

Help on removing the aliases from a MySQL trigger

my question is too easy (I guess), below is an example of trigger that I am trying to remove the aliases. I don't know what I am doing wrong I just can't get it right.
DELIMITER #
CREATE TRIGGER StartOfShift BEFORE INSERT ON shift
FOR EACH ROW
BEGIN
IF(NEW.CashierCode NOT IN ( SELECT w.EmployeeID FROM WorksOn as w
JOIN shop AS s ON w.ShopID = s.ShopID
JOIN CashMachineCode AS c ON s.ShopID = c.ShopID
WHERE c.CashMachineCode = NEW.CashMachineCode ))
THEN SET NEW.CashierCode = NULL;
END IF;
END;
The following should be what you are looking for:
DELIMITER #
CREATE TRIGGER StartOfShift BEFORE INSERT ON shift
FOR EACH ROW
BEGIN
IF(NEW.CashierCode NOT IN (
SELECT WorksOn.EmployeeID FROM WorksOn
JOIN shop ON WorksOn.ShopID = shop.ShopID
JOIN CashMachineCode ON shop.ShopID = CashMachineCode.ShopID
WHERE CashMachineCode.CashMachineCode = NEW.CashMachineCode )
) THEN
SET NEW.CashierCode = NULL;
END IF;
END#
DELIMITER ;