基礎SQL語句-UPDATE

    總有一種感覺,就是csdn這個發表博客的頁面真的是爛的可以。大家可以點擊下面文字的超鏈接,直接看英語文檔。基礎的東西如果不及時回顧,還是會零星的忘記一些。所以看了一下update的操作。

UPDATE [LOW_PRIORITY] [IGNORE] table_reference
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

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. Thetable_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 inSELECT 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.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章