Question:
What is the correct syntax to use when selecting a column value into an UPDATE/INSERT trigger NEW variable?
Details:
Here are the [simplified] tables I am using as well as the query. For the purposes of this example I have chosen something that is recursive, in this case a comment (ie. one can comment on a picture, but also on the comment). At any given time I want to know what picture a comment is commenting on, but I don’t want to query the table n times to get to that picture (hence why I am rejecting the Adjacency List Model), so I have a trigger on insert to copy the target picture over.
PICTURES table:
CREATE TABLE IF NOT EXISTS pictures
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY ( id )
)
COMMENTS table:
CREATE TABLE IF NOT EXISTS comments
(
id INT NOT NULL AUTO_INCREMENT,
picture_id INT NOT NULL,
comment_id INT NOT NULL,
PRIMARY KEY ( id ),
FOREIGN KEY ( picture_id ) REFERENCES pictures ( id ),
FOREIGN KEY ( comment_id ) REFERENCES comments ( id )
)
COMMENTS trigger: Note that NEW.comment_id and NEW.picture_id are NOT NULL, therefore, they default to zero (FALSE). In my actual program I have an XOR to reject invalid attempts to assign both a picture and a comment id.
CREATE TRIGGER bi_comments_fer BEFORE INSERT ON comments FOR EACH ROW
BEGIN
IF ( NEW.comment_id )
THEN
select NEW.picture_id := picture_id from comments where id = NEW.comment_id;
END IF;
END
I tried including an @ sign, like so
select @NEW.picture_id := picture_id from comments where id = NEW.comment_id;
But that also raised a syntax error. Can anyone tell me how to fix this?
1 Answer