I’m trying to set up a MySQL query that will insert a row into table2 if a row in table1 exist already, otherwise it will just insert the row into table1.
I need to find a way to adapt the following query into inserting a row into table2 with the existing row’s id.
INSERT INTO table1 (host, path) VALUES (‘youtube.com’, ‘/watch’) IF NOT
EXISTS ( SELECT * FROM table1 WHERE host=’youtube.com’ AND path=’/watch’ LIMIT 1);
Something kind of like this:
INSERT … IF NOT EXISTS(..) ELSE INSERT INTO table2 (table1_id) VALUES(row.id);
Except I don’t know the syntax for this.
You can use a trigger, a unique or primary key on table1, and INSERT IGNORE.
If you insert in table1 a value which already exists, INSERT IGNORE will not return a duplicate key error.
The trigger will just check if the value already exists in table1 and insert it into table2.
If you need, you can also add an unique key on table2 and use INSERT IGNORE in the trigger.
God luck!