MySQL database update statement

Source: Internet
Author: User
There are two types of SQL statements used to operate databases: Query statements, select statements, and update statements, which are also called data operation statements. This article takes MYSQL as the background to discuss how to enable SQL update statements.

I. insert and replace

Both insert and replace statements Insert new data into the table. The syntax of these two statements is similar. The main difference between them is how to process repeated data.

1. General insert usage

The insert statement in MySQL is not the same as the standard insert statement. In the standard SQL statement, the insert statement that inserts a record at a time has only one form.

Insert into tablename (column name ...) Values (column value );

There is another form in MySQL.

Insert into tablename set
Column_name1 = value1, column_name2 =
Value2 ,...;

The first method separates the column name from the column value. during use, the column name must be consistent with the number of column values. The following statement inserts a record into the users table:

Insert into users (ID,
Name, age) values (123, 'Yao ming ',
25 );

The second method allows the column names and column values to appear and use in pairs. The following statement will produce the same effect.

Insert into users Set ID
= 123, name = 'Yao Ming ', age =
25;

If the set method is used, a value must be assigned to at least one column. If a field uses a missing value (such as default value or auto-increment value), you can omit these fields in either of the two methods. If auto-increment is used in the ID field, the preceding two statements can be written as follows:

Insert into users (name,
Age) values ('Yao Ming ', 25 );

Insert into uses set name = 'Yao Ming ', age =
25;

MySQL has also made some changes in values. If nothing is written in values, MySQL inserts a new record using the default value of each column in the table.

Insert into users ()
Values ();

If nothing is written after the table name, it indicates that all fields in the table are assigned a value. In this way, not only must the value in values be consistent with the number of columns, but the order cannot be reversed.

Insert into users
Values (123, 'Yao ming ',
25 );

If the insert statement is written as follows, MySQL will report an error.

Insert into users
Values ('Yao Ming ', 25 );

2.
Insert multiple records using insert

If you see this title, you may ask, is there anything you can say about it? Won't you be able to insert multiple records after multiple insert statements are called! However, using this method increases the load on the server, because every SQL Server executes the same SQL Analysis and Optimization operations. Fortunately, MySQL provides another solution, that is, using an insert statement to insert multiple records. This is not a standard SQL syntax, so it can only be used in MySQL.

Insert into users (name,
Age) values ('Yao Ming ', 25), ('bill Gates', 50), ('marker', 600 );

Insert
The statement inserts three records into the users table consecutively. It is worth noting that the values of each record must be placed in a pair (…) after values in the preceding insert statement (...) "," Is used in the middle. Suppose there is a table Table1

Create Table Table1 (n
INT );

If you want to insert five records into Table 1, the following statement is incorrect:

Insert into Table1 (I)
Values (1, 2, 3, 4, 5 );

MySQL will throw the following error

Error 1136: column count doesn't match value count at Row 1

The correct statement is as follows:

Insert into Table1 (I)
Values (1), (2), (3), (4), (5 );

Of course, this statement can also omit the column name, so that the number of values in each pair of brackets must be consistent, and this number must be consistent with the number of columns. For example:

Insert into Table1
Values (1), (2), (3), (4), (5 );

3.
Replace statement

We may often encounter this situation when using databases. 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 deletes the original record, and then inserts a new record using insert. MySQL provides us with a new solution, which is the replace statement. Use
When a record is inserted with replace, 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 deletes 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,
B, 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.

Ii. Update

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, update users can be used to update values of multiple fields.
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, C provided by MySQL
The API 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.

Iii. Delete and truncate table

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, truncate
Table deletes 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 and truncate
The tables are the same, but they are different, that is, delete can return the number of deleted records, while truncate table returns 0.

If an auto-increment field exists in a table, use truncate
After table and delete without WHERE clause delete all records, this auto-increment field restores the starting value to 1. if you do not want to do this, you can add the permanent where statement in the delete statement, such as where
1 Or where true.

Delete from Table1 where
1;

The preceding statement scans each record during execution. 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.

Delete and truncate
The biggest difference between tables is that you can use the where statement to select the record to be deleted in Delete. However, the execution speed is not fast. You can also return the number of deleted records. And 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 order
The by and limit clauses 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. 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 sorts records.

Delete from users where
Name = 'Mike 'order by id desc limit 6;

 

 

Related Article

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.