William Orazi
William Orazi

Reputation: 1714

Insert row into another table via mySQL trigger

I'm getting a syntax error when trying to create a trigger to insert a row from one table into another...updating the date and time in the process. Here's my query:

INSERT INTO `second_table` (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12)
  (SELECT `field1`, `field2`, `field3`, `field4`, `field5`, `field6`, `field7`, `field8`, `field9` FROM `first_table` WHERE `field1` = NEW.`field1`), CURDATE(), NOW(), (SELECT `field12` FROM `second_table` WHERE `field1` = NEW.`field1`);

This trigger will run when first_table is updated. I'm not sure if this is the correct way to accomplish the task. I've generalized the field and table names for simplicity.

EDIT:

The columns are identical between the two tables. I just want the ability to update the date and time when the trigger occurs. This works, but obviously just copies the previous date and time:

INSERT INTO `second_table` (SELECT * FROM `first_table` WHERE `field1` = NEW.`field1`);

Upvotes: 0

Views: 955

Answers (1)

scawp
scawp

Reputation: 36

Try:

INSERT INTO `second_table` (field1, field2, field3, field4, field5, field6, field7, field8, field9, field10, field11, field12)
 (SELECT `field1`, `field2`, `field3`, `field4`, `field5`, `field6`, `field7`, `field8`, `field9`, CURDATE() AS `field10`, NOW() AS `field11`, `field12` FROM `first_table` WHERE `field1` = NEW.`field1`);

Upvotes: 2

Related Questions