Is it possible to avoid duplicates in mysql
? I had to search and nothing fits my case, whenever I try to duplicate it.
I'm trying to import this into the table:
INSERT INTO profiles (id, rep, gems, plevel) VALUES (id, 0, 100, 1)
Is it possible to avoid duplicates in mysql
? I had to search and nothing fits my case, whenever I try to duplicate it.
I'm trying to import this into the table:
INSERT INTO profiles (id, rep, gems, plevel) VALUES (id, 0, 100, 1)
To avoid duplication, you must set the key that does not want to be duplicated as PRIMARY KEY
. That is, if you do not want two id's repeated, the column id
must be a PRIMARY KEY
.
That way, when trying to insert a record with the same ID, MySQL will return the error DUPLICATE ENTRY '0' FOR KEY 'id'
.
Try to put ID
as the primary key, and any other values that you do not want to be repeated use the unique
attribute.
Example of creating table with field Unique
:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
Example of changing the structure of the table to be unique
:
ALTER TABLE Persons
ADD UNIQUE (ID);
Remove Unique
:
ALTER TABLE Persons
DROP INDEX UC_Person;
Source: link