mysql mysql 資料存在更新,不存在插入

2021-10-04 02:29:53 字數 1294 閱讀 9209

刪除更新:要求存在唯一索引,主鍵等唯一標識,流程是先刪除再插入,所以永遠可以保證最新。使用replace的最大好處就是可以將delete和insert合二為一,形成乙個原子操作。如果行作為新記錄被insert,則受影響行的值為1;如果原有的記錄被更新,則受影響行的值為2。

-- 刪除更新

replace into golf_game_plan ( create_time, modify_time, user_id, plan_date )

values

( now( ), now( ), 11363, '2019-09-13 00:00:00' );

要求存在唯一索引,主鍵等唯一標識,根據表中唯一索引判斷,如下所示user_id欄位就新增了唯一索引。如果行作為新記錄被insert,則受影響行的值為1;如果原有的記錄被更新,則受影響行的值為2。

-- 唯一索引更新

insert into golf_game_plan ( create_time, modify_time, user_id, plan_date )

values

( now( ), now( ), 11363, '2019-09-13 00:00:00' )

on duplicate key update plan_date = '2019-12-22 00:00:00', modify_time = now();

通過exists語法更新,判斷是否存在記錄,來決定插入或刪除

insert into golf_game_plan ( create_time, modify_time, user_id, plan_date ) select

now( ), now( ), 11369, '2019-09-13 00:00:00'

from

dual

where

not exists ( select * from golf_game_plan where id = 37 );

要求存在唯一索引,主鍵等唯一標識。流程是先刪除再插入。

insert ignore into golf_game_plan ( create_time, modify_time, user_id, plan_date )

values

( now( ), now( ), 11369, '2019-09-13 00:00:00' );

MySql MySql的常見錯誤提示(持續更新)

illegal mix of collations utf8 general ci,implicit and utf8 unicode ci,implicit for operation 字符集不一致造成的,檢視修改標的字符集,改成一致即可。error 1153 08s01 got a packet...

Mysql Mysql資料型別

在設計表時,應該特別重視所用的資料型別。使用錯誤的資料型別可能會嚴重地影響應用程式的功能和效能。更改包含資料的列不是一件小事 而且這樣做可能會導致資料丟失 最常見資料型別 整型 浮點型 字串 日期等 1.1 定長串 char 接受長度固定的字串,其長度是在建立表時指定的。定長列不允許儲存多於指定長度...

MySQL MySQL資料型別總結

資料型別是定義列中可以儲存什麼資料以及該資料實際怎樣儲存的基本規則。資料型別用於以下目的 資料型別允許限制可儲存在列中的資料。資料型別允許在內部更有效地儲存資料。資料型別允許變換排序順序。串資料型別儲存串,如名字,位址,號碼,郵政編號等等。有兩種基本的串型別 定長串和變長串。串資料型別 資料型別 說...