prevent duplicate entries by matching a subset of fields
I have an insert statement that inserts 开发者_StackOverflow中文版tags into a table. Each tag has a unique id
(for referencing), a vid_id
(for matching to a video), and a name
(ex. tag1).
A duplicate entry would be considered having an existing entry with vid_id
and name
as the same as whatever is being inserted.
How do I stop the insert for a duplicate entry that matches 2/3 fields?
$sql="INSERT into tags (id,vid_id,name) VALUES (?,?,?)";
$stmt16 = $conn->prepare($sql);
$result=$stmt16->execute(array($id,$vid_id,$tag));
You just have to create a unique contraint composed by vid_id
and name
and you are all set!
This is how you do it:
alter table tags add unique (vid_id, name);
Once created, your unique constraint will forbid the insertion of values that would produce duplicate rows given your unique definition (the fields involved).
That's also true for updates (ah, have you though of that?): if you try to update a record and the update will produce a duplicate, the unique constraint will block it.
create a unique index on these 2 columns.
精彩评论