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!
INSERT INTO groupdentlink (
f_dent_id, f_group_id, f_schedule_id
) SELECT
'$_POST[id]' f_dent_id,
'$groupid' f_group_id,
'$scheduleid' f_schedule_id
FROM DUAL
WHERE NOT EXISTS (
SELECT 1
FROM `groupdentlink`
WHERE
f_dent_id = '$_POST[id]' AND f_group_id = '$groupid'
LIMIT 1 -- will stop mysql to stop searching after first match
)
You don't need primary keys to make MySQL handle this for you, you should add a UNIQUE
key constraint on the combined set of the two columns.
Query to add the unique key dent_group_uniq_key
to groupdentlink
.
ALTER TABLE groupdentlink ADD UNIQUE KEY `dent_group_uniq_key` (
f_dent_id, f_group_id
);
Then use INSERT IGNORE
on your query:
INSERT IGNORE INTO groupdentlink (
f_dent_id, f_group_id, f_schedule_id
) VALUES (
'$_POST[id]', '$groupid', '$scheduleid'
)
INSERT IGNORE
will try to insert a row to your table, if it fails due to a key constraint it will act like nothing happen.
INSERT INTO groupdentlink (f_dent_id, f_group_id, f_schedule_id)
SELECT '$_POST[id]', '$groupid', '$scheduleid' FROM dual
WHERE NOT EXISTS (
select * from groupdentlink
where f_dent_id='$_POST[id]'
and f_group_id='$groupid'
)
And I think you can create a composite primary key on the combination (f_dent_id, f_group_id) just to make sure.
You've almost got it! You can use a select statement to feed an insert statement. Just do this:
INSERT INTO groupdentlink (f_dent_id, f_group_id, f_schedule_id)
SELECT '$_POST[id]', '$groupid', '$scheduleid'
WHERE
NOT EXISTS (
select
1
from
groupdentlink
where
f_dent_id = $_POST[id]
and f_group_id = '$groupid'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With