prevent duplicate entries by matching a subset of fields - mysql

I have an insert statement that inserts 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.

Related

Insertig datas, if not exists

I have SQL code, how should I change it to insert datas only if they aren't exist in my table. thanks for your answers:)
INSERT INTO stages_done(id_booked_proj, id_stage)
SELECT booked_proj.id, stages.id_st
FROM booked_proj, stages
WHERE booked_proj.name='home' AND stages.name_st= 'sm'"
You can use INSERT IGNORE, this way the row won't be inserted if it results in a duplicate key:
INSERT IGNORE INTO stages_done(id_booked_proj, id_stage)
SELECT booked_proj.id, stages.id_st
FROM booked_proj, stages
WHERE booked_proj.name='home' AND stages.name_st= 'sm'"
Any duplicate key in columns either with PRIMARY KEY or UNIQUE constraints will be ignored.
If you have writing access, you can add a constraint to your table, like this:
ALTER TABLE `stages_done` ADD UNIQUE `id_booked_proj_id_stage_index` (`id_booked_proj`, `id_stage`);
Where id_booked_proj_id_stage_index can be any name you pick as long as it is unique.

Duplicate Primary Key while populating new table from old table

I've created multiple indexed tables that I want to tie into a new normalized version of an old table. I get everything indexed and the relations set and I get a "Duplicate entry '11' for key 'Primary' " error message.
Here's the code I'm using to populate the new table.
insert into dvdNormal(dvdId, dvdTitle, year, publicRating, dvdStudioId,
dvdStatusId, dvdGenreId)
(
select dvdId, dvdTitle, year, publicRating, studioId, statusId, genreId
from dvd d
join dvdStudio on d.studio = dvdStudio.studioName
join dvdStatus on d.status = dvdStatus.dvdStatus
join dvdGenre on d.genre = dvdGenre.genre);
I'm going to assume you were asking a question, and not just giving a status report.
The behavior you observe is (most likely) due to the insert statement attempting to insert a row that violates a UNIQUE (or PRIMARY KEY) constraint defined on the dvdId column in the target table (the table the statment is inserting rows into.)
And either 1) the dvdId column is not unique in the table it's being retrieved from, or 2) there is more than one "matching" row in one of the other three tables.
For example, if dvdId is a column in dvd, and it's defined as UNIQUE, then case 1) doesn't apply.
But if that row from dvd has more than one "matching" row from one (or more) of the other three tables, then we'd expect the SELECT to generate "duplicate" values for dvdId.
For example, if the genre column is not unique in dvdGenre table, or studioName column is not unique in dvdStudio, we'd expect the query to return multiple copies of the row from dvd. The redundant data (duplicated values) is expected when we "denormalize" data.
If we want to get the table loaded from the query, there's a couple of options.
If we want to store every row returned by the query, we would remove the UNIQUE constraint from the dvdId column. (There may also be other UNIQUE constraints that need to be removed from the target table.)
If we only want to store one copy of the row from dvd, along with values from one matching row from each of the other tables, we could leave the UNIQUE constraint, and use an INSERT IGNORE statement to avoid throwing a "duplicate key error". Any rows where that error would have been thrown will be discarded, and won't be inserted into the target table.
Because the column references aren't qualified, we can't actually tell which table the dvdId column is beint returned from. We can't tell which table any of the columns are returned from. We can "guess" that genreId is being returned from the dvdGenre table, but for us to figure that out, we'd need to investigate the schema definition. It's not a problem for MySQL, it can lookup the table definitions a whole lot faster than we can.
We could aid to the future reader of that SQL statement by qualifying the column references with the tablename, or a table alias.

Strategies for preventing the insertion of duplicate table rows

Scenario:
User A and B executes at the same time select id from Product where id = ?, if the there are no results, both create a new product with given ID.
Problem:
This could lead to the creation of duplicate rows.
Question:
What are the possibles strategies to prevent that? I know that I can use compound/unique keys, to guarantee this, but are there any other strategies? Is there any SQL statement to lock query with same parameters?
You can use unique constraints
ALTER TABLE Persons ADD UNIQUE (P_Id)
or
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
That way it would be impossible for a duplicate to be inserted.
Put a UNIQUE key on the field in question:
https://dev.mysql.com/doc/refman/5.0/en/constraint-primary-key.html

Duplicate key update MySQL not updating

I have two Unique keys in one table. I'm inserting the data from an csv file.
Unique keys are: enrollmentNo and subjectCode
My query is:
Insert into result_stud_det(enrollmentNo,departmentCode,subjectCode,semester,marks,enrSubjCode) values (?,?,?,?,?,?) "
+ "ON DUPLICATE KEY UPDATE previousMarks=marks, marks=?;
The problem appeared when the data is updating. The "marks" updating in the end is remaining same. The first data on the csv file is copied down to every other column with unique enrollmentNo and to any subjectCodes.
It is because it is looking for the unique key "enrollmentNo" only.
What do I need to do so that the latest marks, "marks", doesn't have same value after updating it?
I suspect your problem is related to this question: MySQL behavior of ON DUPLICATE KEY UPDATE for multiple UNIQUE fields
From the accepted answer:
UPDATE in ON DUPLICATE KEY UPDATE is performed if one of the UNIQUE field equals the value to be inserted
It sounds like you are expecting your statement to behave as if you have a single, composite unique key, instead of two separate unique keys.

check duplication using mysql select

I have a category say ecommerce.add ebay and amazon.when i update ebay as amazon,it should n't update.How do i d it?
I suggest you check out unique indexes and primary keys. These will cause an insert or update to fail rather that allow duplicate entries to be made.
CREATE UNIQUE INDEX name_unique ON tablename (name(10));
Replace name_unique with the name you want for the index, tablename with the name of your table, and name(10) with the column name and how many characters you want to be unique (the length of the column if you want the entire value to be unique).