I have 3 tables: dentists, groups, and groupdentlink. Many dentists link to many groups through the groupdentlink table.
So I’m trying to make a query where it will insert rows into groupdentlink (linking all dentists in the state with all the groups in the state) but only if those rows don’t already exist. In a nutshell I want to add new rows without overwriting existing ones or duplicating them.
So the intent of the query is something like:
INSERT INTO groupdentlink (f_dent_id, f_group_id, f_schedule_id)
VALUES ('$_POST[id]', '$groupid', '$scheduleid')
WHERE NOT EXISTS ('$_POST[id]', '$groupid')
And I don’t have any primary keys in the groupdentlink table.
Thank you in advance!
If you really want to write your own (working) query..
… but MySQL can handle all this for you!
You don’t need primary keys to make MySQL handle this for you, you should add a
UNIQUEkey constraint on the combined set of the two columns.Query to add the unique key
dent_group_uniq_keytogroupdentlink.Then use
INSERT IGNOREon your query:INSERT IGNOREwill try to insert a row to your table, if it fails due to a key constraint it will act like nothing happen.