REPLACE INTO statement and a unique index UNIQUE INDEX

In development, we often use the REPLACE INTO statements, the following content is in the course of my little notes.

1. The number of rows on the affected

After using REPLACE INTO statement will show the number of rows affected, there are two issues, namely: 1 or greater than 1.

1.1 The number of rows affected 1

DESCRIPTION REPLACE INTO statement does not replace original data in the data table, at this time corresponds to a REPLACE INTO statement INSERT statement

1.2 is greater than the number of rows affected 1

2 are generally described REPLACE INTO statement replaces the original data in the data table, which is to delete a row of data in the data table, and INSERT a row of data.

2. The only index

REPLACE and INSERT operation is very similar. Only one exception, if an old record in the table for a PRIMARY
KEY or UNIQUE index a new record having the same value, before the new record is inserted, the old record is deleted.
Note that unless the table has a PRIMARY KEY or UNIQUE index, otherwise, use a REPLACE statement makes no sense. The
statement with the INSERT same, because no index is used to determine whether a new row duplicates other lines.

Because usually we will set up the primary key id, and id have generally unrepeatable characteristics, we typically use a unique index to limit the data in the data table, for example: we do not want to duplicate data there a phone number, we can phone the number field is set to a unique index, so that if we have the same phone number information will not be inserted.

3. Examples

First we create a table with an auto-increment primary key and unique index.

CREATE TABLE example 
(
`id`  int NOT NULL AUTO_INCREMENT ,
`name`  varchar(255) NOT NULL ,
`gender`  varchar(255) NOT NULL ,
`age`  int NOT NULL ,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `test_index`(`name`,`gender`) USING BTREE
)

We will name and sex as co-unique index.
Insert a piece of data.

INSERT INTO example (name,gender,age) values ("王大锤",0,18)

Now, the data in the table is the situation
Here Insert Picture Description
Next, we try to insert a same name and gender, but different age data

INSERT INTO example (name,gender,age) values ("王大锤",0,19)

The results will complain
Here Insert Picture Description
then we try to use REPLACE INTO statement

REPLACE INTO example (name,gender,age) values ("王大锤",0,19)

sql statement runs successfully, you can see the number of rows affected is 2
Here Insert Picture Description
data and then look at the table
Here Insert Picture Description
here have a question, Why is auto-incremented id will direct from a 1 to a 3, hoping to have a big God help me to answer.

Published 19 original articles · won praise 4 · Views 1533

Guess you like

Origin blog.csdn.net/DATANGguanjunhou/article/details/104506111