Im using PDO (PHP Data Objects) for database interactions from PHP. This question concerns three database tables: two are just standard tables with primary keys, and the other is a table to describe relations between those other two tables. As such it has no primary key, but 2 foreign key columns (table_1_id and table_2_id). Neither can be unique as there is a many to many relationship between records in the other two tables.
To determine if a relationship should be added, I need to insert a record only if there is not already a row in the relational table which matches both table_1_id AND table_2_id.
Ideally my insert would look like this:
INSERT INTO table_3 (table_1_id, table_2_id) VALUES (:id1, :id2)
WHERE NOT EXISTS (
SELECT 1 FROM table_3 WHERE table_1_id = :id1 AND table_2_id = :id2
)
However, I know this is not valid SQL. I have looked around a bit and can't determine the best way to do this.
Thanks for your help