Avoid duplication in Mysql

Asked

Viewed 170 times

1

Duplication of mysql ? I’ve been searching and nothing fits my case, every time I try to duplicate it.

I’m trying to import it on the table: INSERT INTO profiles (id, rep, gems, plevel) VALUES (id, 0, 100, 1)

  • You want to avoid having Inserts with equal values?

2 answers

4


To avoid duplication, you must set the key you do not want to be duplicated as PRIMARY KEY. That is, if you don’t want two repeated id’s, the column id must be a PRIMARY KEY. This way, when you try to insert a record with the same ID, Mysql will return the error DUPLICATE ENTRY '0' FOR KEY 'id'.

1

Try to put the ID as the primary key, and the other values you do not want to be repeated use the attribute unique.

Example of table creation 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 table structure to be unique:

ALTER TABLE Persons
ADD UNIQUE (ID);

Remove Unique:

ALTER TABLE Persons
DROP INDEX UC_Person;

Source: https://www.w3schools.com/sql/sql_unique.asp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.