error 1093: MySQL can’t specify target table 'SENTIERO' for update in FROM clause
This is my trigger:
CREATE TRIGGER lunghezza_sentiero_datoderivato_INSERT
AFTER INSERT ON SENTIERO_HA_TAPPA
FOR EACH ROW
BEGIN
UPDATE SENTIERO
SET lunghezza= (SELECT SUM(lunghezza)
FROM TAPPA, SENTIERO as S2, SENTIERO_HA_TAPPA
WHERE NEW.IDsentiero=S2.IDsentiero
and SENTIERO_HA_TAPPA.IDtappa=TAPPA.IDtappa);
WHERE IDsentiero IN (SELECT IDsentiero
FROM TAPPA, SENTIERO, SENTIERO_HA_TAPPA
WHERE SENTIERO_HA_TAPPA.IDsentiero=SENTIERO.IDsentiero
and NEW.IDtappa=SENTIERO_HA_TAPPA.IDtappa);
END$$
I’ve found this article about this issue, check it on
http://verysimple.com/2011/03/30/mysql-cant-specify-target-table-for-update-in-from-clause/
Is it the only chance i have? Please help me
EDIT:: i’ve just added the ‘WHERE’ clause but it signals me “error syntax”… why?
Try this instead:
Update:
You have to get the sum of the values of
lunghezzafrom theTAPPAtable not from theSENTIERO, thats why you were gettingNULLvalues. So the finalCREATE TRIGGERcode should be like this:SQL Fiddle Demo
Note that: This trigger will update the values of
lunghezzain the tableSENTIERO, when any row being inserted into the tableSENTIERO_HA_TAPPAfor all theIDsentieroin theSENTIERO, not just the value of the new insertedIDsentiero.To update only the value of
lunghezzafor the new inserted value ofIDsentierointo the tableSENTIERO_HA_TAPPAonly, add aWHERE S2.IDsentiero = NEW.IDsentieroto theUPDATEstatement of the trigger. Like this:For instance, if you create the three tables, then insert the data to the tables and then create that trigger. Then do an insert into the table
SENTIERO_HA_TAPPAlike this:Then the trigger will update the value of the
IDsentiero = 4only in the tableSENTIERO, not all the values of it. And the values oflunghezzafor otherIDsentiero‘s will beNULLs:So, you have to create your tables and the triggers before any insert. Then do the insertions into the tables, so that you get a consistent data. That’s how it should work.
Like in the following demo:
Note that: In all the demos in this answer, I used only the three tables involved with the trigger, also I modified the two fields
inizio,fineto be nullable in the tableTAPPA, because your insert clauses into that table haveNULLvalues to those columns.