so i’ve edited my code
i had this problem in another trigger but this time even changing WHERE clause doesn’t help
DELIMITER $$
CREATE TRIGGER pic_album_change AFTER UPDATE ON pictures
FOR EACH ROW BEGIN
UPDATE albums SET counter = counter + 1 WHERE albums.id = NEW.album_id;
UPDATE albums SET counter = counter - 1 WHERE albums.id = OLD.album_id;
END $$
DELIMITER ;
error :
<p>Error Number: 1442</p><p>Can't update table 'pictures' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
i dont see any changes on the pictures table in this trigger
i have another trigger that involves these two tables
DELIMITER $$
CREATE TRIGGER album_change
AFTER UPDATE
ON albums
FOR EACH ROW
BEGIN
UPDATE pictures
SET
level = NEW.level
WHERE
pictures.album_id = NEW.id ;
END $$
DELIMITER ;
Your
WHEREclause is the wrong way round.would cause
albums.counterto be incremented (presumably that’s the number of pictures in each album).It matters because joins on tables are not commutative — the direction of the join is important. Here you need to find the record in
albumsto update based on the value of the row inpictures.While in this case there isn’t really any ambiguity, SQL needs to follow rules about joins.
The issue with your second trigger is that MySQL is preventing a continuous cycle of updates. You have a trigger
pic_album_changewhich updatesalbumswhenpicturesis updated. And you have a triggeralbum_changewhich updatespictureswhenalbumsis updated. Those triggers will trigger each other.It seems to me that the database design may need to be changed. Do you really need
albums.counterwhen that data can be found withSELECT count(*) FROM pictures WHERE album_id=...? It should be possible to normalise data so that there no circular references in triggers. In fact triggers may not be necessary at all.