mysql語句 批量更新多條記錄的不同值

2021-09-07 12:08:42 字數 1947 閱讀 5469

【簡介】

mysql更新語句很簡單,更新一條資料的某個字段,一般這樣寫:

update mytable set myfield = \'value\' where other_field = \'other_value\';

如果更新同一欄位為同乙個值,mysql也很簡單,修改下where即可:

update mytable set myfield = \'value\' where other_field in (\'other_values\');

這裡注意 『other_values』 是乙個逗號(,)分隔的字串,如:1,2,3

那如果更新多條資料為不同的值,可能很多人會這樣寫:

foreach ($display_order as $id => $ordinal)

即是迴圈一條一條的更新記錄。一條記錄update一次,這樣效能很差,也很容易造成阻塞。

那麼能不能一條sql語句實現批量更新呢?mysql並沒有提供直接的方法來實現批量更新,但是可以用點小技巧來實現。

update mytable

set myfield = case id

when 1 then \'value\'

when 2 then \'value\'

when 3 then \'value\'

endwhere id in (1,2,3)

這裡使用了case when 這個小技巧來實現批量更新。

舉個例子:

update categories

set display_order = case id

when 1 then 3

when 2 then 4

when 3 then 5

endwhere id in (1,2,3)

這句sql的意思是,更新display_order 字段,如果id=1 則display_order 的值為3,如果id=2 則 display_order 的值為4,如果id=3 則 display_order 的值為5。

即是將條件語句寫在了一起。

這裡的where部分不影響**的執行,但是會提高sql執行的效率。確保sql語句僅執行需要修改的行數,這裡只有3條資料進行更新,而where子句確保只有3行資料執行。

如果更新多個值的話,只需要稍加修改:

update categories

set display_order = case id

when 1 then 3

when 2 then 4

when 3 then 5

end,

title = case id

when 1 then \'new title 1\'

when 2 then \'new title 2\'

when 3 then \'new title 3\'

endwhere id in (1,2,3)

到這裡,已經完成一條mysql語句更新多條記錄了。

但是要在業務中運用,需要結合服務端語言,這裡以php為例,構造這條mysql語句:

$display_order = array(

1 => 4,

2 => 1,

3 => 2,

4 => 3,

5 => 9,

6 => 5,

7 => 8,

8 => 9

);$ids = implode(\',\', array_keys($display_order));

$sql = \"update categories set display_order = case id \";

foreach ($display_order as $id => $ordinal)

$sql .= \"end where id in ($ids)\";

echo $sql;

這個例子,有8條記錄進行更新。**也很容易理解,你學會了嗎?    

mysql語句 批量更新多條記錄的不同值

mysql更新語句很簡單,更新一條資料的某個字段,一般這樣寫 update mytable set myfield value where other field other value 如果更新同一欄位為同乙個值,mysql也很簡單,修改下where即可 update mytable set my...

MySQL批量更新語句

update mytable set myfield case id when 1then value when 2then value when 3then value endwhere id in 1,2,3 例如 update categories set display order case...

mysql多條更新

最近在完成mysql專案整合的情況下,需要增加批量更新的功能,根據網上的資料整理了一下,很好用,都測試過,可以直接使用。mysql 批量更新共有以下四種辦法 1 replace into 批量更新 replace into test tbl id,dr values 1,2 2,3 x,y 例子 r...