How to Use Insert/replace/update/delete in MySQL

Source: Internet
Author: User
1. insert: (1) Insert multiple records simultaneously Insert into tab (col1, col2, col3) values (a1, a2, a3), (b1, b2, b3), (c1, c2, c3); compared to multiple insert records, this method reduces the number of SQL Analysis and Optimization times, thus reducing the burden on the server, improves the insert record efficiency. (2) Insert a record (if you use the SET method, you must assign a value to at least one column .) Insert into tab set col1 = a1, col2 = a2, col3 = a3; <=> Insert into tab (col1, col2, col3) values (a1, a2, a3); 2. the use of replace (http://hi.baidu.com/neonway/blog/item/51c4c158e1b996dd9d820459.html) we may often encounter this situation when using the database. If a table creates a unique index on a field and inserts a record into the table using an existing key value, a primary key conflict error is thrown. Of course, we may want to overwrite the original record value with the new record value. If you use the traditional method, you must first use the DELETE statement to DELETE the original record, and then use INSERT to INSERT a new record. MySQL provides us with a new solution, which is the REPLACE statement. When you use REPLACE to INSERT a record, if there is no duplicate record, REPLACE is the same as the INSERT function. If there is a duplicate record, REPLACE replaces the original record value with the value of the new record.

The biggest advantage of using REPLACE is that you can combine DELETE and INSERT into one to form an atomic operation. In this way, you do not have to consider complicated operations such as adding transactions when using both DELETE and INSERT.

When using REPLACE, the table must have a unique index, and the field where the index is located cannot allow null values. Otherwise, REPLACE is exactly the same as INSERT.

After REPLACE is executed, the system returns the affected number of rows. If 1 is returned, no duplicate records exist in the table. If 2 is returned, a duplicate record exists, the system automatically calls DELETE to DELETE this record, and then inserts this record with INSERT. If the returned value is greater than 2, multiple unique indexes exist, and multiple records are deleted and inserted.

The REPLACE syntax is very similar to INSERT. The following REPLACE statement inserts or updates a record.

Replace into users (id, name, age) VALUES (123, 'zhao Benshan ', 50 );
Insert multiple records:

Replace into users (id, name, age)

VALUES (123, 'zhao Benshan ', 50), (134, 'Mary', 15 );

REPLACE can also use the SET statement.

Replace into users SET id = 123, name = 'zhao Benshan ', age = 50;

As mentioned above, REPLACE may affect more than three records because there is more than one unique index in the table. In this case, REPLACE considers each unique index, deletes the duplicate record corresponding to each index, and inserts this new record. Assume that there is a table 1 with three fields a, B, and c. They all have a unique index.

Create table table1 (a int not null unique, B INT NOT NULL UNIQUE, c INT NOT NULL UNIQUE );

Assume that three records exist in table 1.

A B c

1 1 1

2 2 2

3 3 3

Next, we use the REPLACE statement to insert a record to table 1.

Replace into table1 (a, B, c) VALUES (1, 2, 3 );

The returned result is as follows:

Query OK, 4 rows affected (0.00 sec)

The record in table 1 is as follows:

A B c

1 2 3

As we can see, REPLACE deletes all the three original records and inserts (1, 2, 3. 3. update (http://hi.baidu.com/neonway/blog/item/51c4c158e1b996dd9d820459.html) update and insert/replace return the number of updated records, all returned through the row_count () function. But here is an exception, as mentioned in my previous article (the function used to calculate the number of rows affected by SQL statements in MySQL, the number of returned records does not include records that meet the WHERE condition but are not updated. UPDATE is used to UPDATE data in a table. This syntax is similar to the second INSERT syntax. The table name and SET expression must be provided. You can add the WHERE clause to limit the range of updated records.

UPDATE table_anem SET column_name1 = value1, column_name2 = value2 ,...

WHERE ...;

The following statement changes the age of the record whose id is 123 in the users table to 24.

UPDATE users' SET age = 24 WHERE id = 123;

Similarly, you can use UPDATE to UPDATE the values of multiple fields: UPDATE users SET age = 24, name = 'Mike 'WHERE id = 123;

The above UPDATE statement specifies a condition through WHERE. Otherwise, UPDATE updates the values of all records in the table.

If the type of the updated field does not match the assigned value when the UPDATE record is used, MySQL converts the value to a value of the corresponding type. If the field is of the numerical type and the value is assigned beyond the maximum range of the Data Type, MySQL converts the value to the maximum or minimum value of the range. If the string is too long, MySQL will cut off the extra strings. If you set a non-empty field to null, set this field to their default value. The default value of the number is 0, and the default value of the string is a null string (not null, it is ""). In either case, UPDATE does not affect the data in the table.

1. When the WHERE condition does not match the record in the table.

2. When we assign the same value to a field, for example, assign the field abc to '123', and the original value of abc is '123 '.

Like INSERT and REPLACE, UPDATE also returns the number of updated records. However, these records do not include records that meet the WHERE condition but are not updated. The following UPDATE statement does not UPDATE any records.

UPDATE users SET age = 30 WHERE id = 12;

Query OK, 0 rows affected (0.00 sec)

Note that if the type of a field is TIMESTAMP, this field is automatically updated when other fields are updated.

In some cases, we need to get the number of rows selected for UPDATE, rather than the number of rows to be updated. We can achieve this through some APIs. For example, the c api provided by MySQL provides an option to obtain the number of records you want. The default number of records obtained by the JDBC driver of MySQL is also the number of matching records.

UPDATE and REPLACE are similar, but there are two differences between them.

1. UPDATE does not do anything when there is no matching record, while REPLACE is updated when there is a duplicate record and inserted when there is no duplicate record.

2. UPDATE can selectively UPDATE some fields of a record. REPLACE deletes this record and inserts a new record when it finds a duplicate record. That is, all fields are updated. 4. delete (http://hi.baidu.com/neonway/blog/item/51c4c158e1b996dd9d820459.html)

There are two ways to DELETE data in MySQL: one is the DELETE statement and the other is the truncate table statement. You can use the WHERE clause to select the record to be deleted. However, using truncate table will delete all records in the TABLE. Therefore, the DELETE statement is more flexible.

To clear all records in the table, you can use the following two methods:

Delete from table1

Truncate table table1

The TABLE in the second record is optional.

To DELETE some records in a table, you can only use the DELETE statement.

Delete from table1 WHERE ...;

If DELETE does not add a WHERE clause, it is the same as the truncate table, but they are a little different. That is, DELETE can return the number of deleted records, while the truncate table returns 0.

If an auto-increment field exists in a TABLE, use truncate table.

Delete from table1 WHERE 1; each record is scanned when the preceding statement is executed. But it is not compared, because the WHERE condition is always true. In this way, although the maximum auto-increment value can be maintained, because it scans all records, the execution cost is much greater than the DELETE without the WHERE clause.
The biggest difference between DELETE and truncate table is that DELETE can use the WHERE statement to select the record to be deleted. However, the execution speed is not fast. You can also return the number of deleted records. The truncate table cannot delete the specified record, and the deleted record cannot be returned. But it runs very fast.

Unlike standard SQL statements, DELETE supports the ORDER BY and LIMIT clauses, which allow us to better control the records to be deleted. For example, if you only want to delete part of the records filtered out BY the WHERE clause, you can use LIMIB. If you want to delete the last few records, you can use order by and LIMIT together. Suppose we want to delete the first six records whose name is "Mike" in the users table. You can use the following DELETE statement:

Delete from users WHERE name = 'Mike 'LIMIT 6;

Generally, MySQL does not determine which 6 records are deleted. To be more secure, we can use order by to sort the records.

Delete from users WHERE name = 'Mike 'order by id desc limit 6;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.