mysql 資料庫插入語句之insert into,replace into ,insert ignore,replaceignore

來源:互聯網
上載者:User

mysql 資料庫插入語句之insert into,replace into ,insert ignore,replaceignore

最近才發現mysql的插入語句居然有如此多的用法,這裡拿來分享一下.

①關於insert into :

  insert into table_name values();

  insert into table_name (column) values ();

  insert into table_name values(select (column) from table_name2);

這裡的插入只需要注意一點的就是:

如果發生主鍵衝突,(也就是插入的主鍵已經在表中存在時),系統報錯.

②replace into :

  replace into 跟 insert into 功能類似,不同點在於:replace into 首先嘗試插入資料到表中, 1. 如果發現表中已經有此行資料(根據主鍵或者唯一索引判斷)則先刪除此行資料,然後插入新的資料。 2. 否則,直接插入新資料。
要注意的是:插入資料的表必須有主鍵或者是唯一索引!否則的話,replace into 會直接插入資料,這將導致表中出現重複的資料。

③insert ignore into

  insert ignore into 與 insert into 的主要區別在於當發生主鍵衝突的時候,系統不會報錯,直接跳過該條記錄的插入.

感覺是不是很有意思呢...

下面我們來做個實驗.

create table test (

`id`  int(11) not null  auto_increment comment '主鍵',

`name` varchar(20) not null comment '姓名',

primary key (`id`)

)ENGINE=InnoDB DEFAULT CHARSET utf8 comment='測試表';


然後我們插入幾條資料進去.

insert into test (name) values ('vein');

insert into test (name) values ('vein1');

insert into test (name) values ('vein2');

當執行下面這條語句時:

insert into test (id,name) values (1,'vein11');

系統會報錯,說主鍵衝突.

如果執行下面的語句時:

insert ignore into test (id,name) values (1,'vein11');

系統不會報錯,直接忽略.

replace into test(id,name) values(1,'vein11');

系統插入成功,並且修改表中記錄為

1, vein11.


Edited by VeinQueen 




對於mysql語句的INSERT

先查詢出來然後再 插入
 
mysql插入與更新問題

據我所知,你這個沒法用一條SQL語句搞定吧,得分開寫,
 

相關文章

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.