您的位置:首页 > 数据库

基础SQL语句-UPDATE

2016-01-24 15:13 786 查看
    总有一种感觉,就是csdn这个发表博客的页面真的是烂的可以。大家可以点击下面文字的超链接,直接看英语文档。基础的东西如果不及时回顾,还是会零星的忘记一些。所以看了一下update的操作。

UPDATE [LOW_PRIORITY] [IGNORE] [code]table_reference

SET
col_name1
={
expr1
|DEFAULT} [,
col_name2
={
expr2
|DEFAULT}] ...
[WHERE
where_condition
]
[ORDER BY ...]
[LIMIT
row_count
][/code]

If you access a column from the table to be updated in an expression, 
UPDATE
 uses
the current value of the column. For example, the following statement sets 
col1
 to
one more than its current value:
UPDATE t1 SET col1 = col1 + 1;


    下面的语句执行的结果是col1和col2拥有相同的值。单表的update操作从左到右执行。如果你更新的值等于目前的值,mysql并不会执行更新操作。
UPDATE t1 SET col1 = col1 + 1, col2 = col1;


    在NOT NULL类型的列被更新为NULL时,严格个SQL模式会发生错误。否则,该列会被设置成合法的默认值。如果是数值类型会被设置成0,字符串类型设置成空字符,以及日期和时间也会被设置成“zero”值。See Section
11.6, “Data Type Default Values”.

    更新操作返回受影响的行数。

    我们可以使用limit row_count来限制更新的范围。更新会在更新了符合where条件的row_count条数据之后停止操作。

    如果一个更新操作有order by语句,则更新会按照指定的顺序进行更新。这个操作在恰当的场合会很有用,尤其是更新唯一自增索引的时候,比如下面的sql语句就会有错误。
UPDATE t SET id = id + 1;


    举个例子,如果一个表包含1和2,在2更新为3之前就会发生error。去避免这个问题,增加一个order by语句,保证大的id更新在小的id之前。
UPDATE t SET id = id + 1 ORDER BY id DESC;


You can also perform 
UPDATE
 operations
covering multiple tables. However, you cannot use 
ORDER BY
 or 
LIMIT
 with
a multiple-table 
UPDATE
.
The
table_references
 clause
lists the tables involved in the join. Its syntax is described in Section
13.2.9.2, “JOIN Syntax”. Here is an example:
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;


The preceding example shows an inner join that uses the comma operator, but multiple-table 
UPDATE
 statements
can use any type of join permitted in
SELECT
 statements,
such as 
LEFT JOIN
.

If you use a multiple-table 
UPDATE
 statement
involving 
InnoDB
 tables for which
there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. In this case, the statement fails and rolls back. Instead, update a single table and rely on the 
ON
UPDATE
 capabilities that 
InnoDB
 provides
to cause the other tables to be modified accordingly. See Section
14.8.6, “InnoDB and FOREIGN KEY Constraints”.

You cannot update a table and select from the same table in a subquery.

Index hints (see Section
8.9.3, “Index Hints”) are accepted for 
UPDATE
 statements,
but are ignored prior to MySQL 5.5.6.

An 
UPDATE
 on a partitioned table
using a storage engine such as 
MyISAM
 that
employs table-level locks locks all partitions of the table. This does not occur with tables using storage engines such as 
InnoDB
 that
employ row-level locking. This issue is resolved in MySQL 5.6. See Section
19.5.4, “Partitioning and Table-Level Locking”, for more information.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  2016 mysql sql