Compare Two MySQL Tables and Insert Missing IDs

Hi,

What’s the correct way to compare two tables and update table 2 with any missing IDs?

Scenario:

Table 1: has primary key column ‘id’
Table 2: has foreign key column ‘related_id’ linked to Table 1 ‘id’ column
Compare the two tables and insert any missing IDs into table 2 foreign_key ‘related_id’ column

This returns any records in table 1 that are not in table 2, I’m not sure how to combine an insert of the missing records into table 2 ?

SELECT id FROM table1 WHERE id NOT IN (SELECT related_id FROM table2)

OK, I figured it out:

INSERT Into table2 (related_id) SELECT id FROM table1 WHERE id NOT IN (SELECT related_id FROM table2)
Sponsor our Newsletter | Privacy Policy | Terms of Service