MySQL中的insert into类似用法

来源:互联网 发布:泳衣女款淘宝网 编辑:程序博客网 时间:2024/06/05 09:13
1、insert into
insert into表示插入数据,数据库会检查主键(PrimaryKey),如果出现重复会报错。

2、insert ignore into
当插入数据时,如出现错误时,如重复数据,将不返回错误,只以警告形式返回。所以使用ignore请确保语句本身没有问题,否则也会被忽略掉。insert ignore表示,如果中已经存在相同的记录,则忽略当前新数据。
INSERT IGNORE INTO books (name) VALUES ('MySQL Manual')

3、replace into
如果存在primary or unique相同的记录,则先删除掉。再插入新记录。如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空。
replace into表示插入替换数据,需求表中有PrimaryKey,或者unique索引的话,如果数据库已经存在数据,则用新数据替换,如果没有数据效果则和insert into一样。
REPLACE INTO books SELECT 1, 'MySQL Manual' FROM books

4、on duplicate key update
当primary或者unique重复时,则执行update语句,在原有记录基础上,更新指定字段内容,其它字段内容保留。如update后为无用语句,如id=id,则同1功能相同,但错误不会被忽略掉。
例如,为了实现name重复的数据插入不报错,可使用一下语句:
INSERT INTO books (name) VALUES ('MySQL Manual') ON duplicate KEY UPDATE id = id;

5、insert … select … where not exist
根据select的条件判断是否插入,可以不光通过primary 和unique来判断,也可通过其它条件。例如:
INSERT INTO books (name) SELECT 'MySQL Manual' FROM dual WHERE NOT EXISTS (SELECT id FROM books WHERE id = 1)

注:如果使用的是insert into 发现重复的会报错,而insert ignore  into 发现将要插入的数据行中包含唯一索引的字段值已存在,会丢弃掉这行数据,不做任何处理;REPLACE发现重复的先删除再插入,如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空。

示例代码:
create table tab_mysqlinsert_tets(id int not null primary key,name varchar(50),age int);insert into tab_mysqlinsert_tets(id,name,age)values(1,"bb",13);select * from tab_mysqlinsert_tets;insert ignore into tab_mysqlinsert_tets(id,name,age)values(1,"aa",13);select * from tab_mysqlinsert_tets;//仍是1,“bb”,13,因为id是主键,出现主键重复但使用了ignore则错误被忽略replace into tab_mysqlinsert_tets(id,name,age)values(1,"aa",12);select * from tab_mysqlinsert_tets; //数据变为1,"aa",12insert into tab_mysqlinsert_tets (name) values ('mysql manual') on duplicate key update id = id;select * from tab_mysqlinsert_tets;insert into tab_mysqlinsert_tets (id,name) values (0,'mysql manual test') on duplicate key update age = 100;select * from tab_mysqlinsert_tets;insert into tab_mysqlinsert_tets (name) select 'mysql manual where no exists' from dual where not exists (select id from tab_mysqlinsert_tets where id = 1);select * from tab_mysqlinsert_tets;insert into tab_mysqlinsert_tets (id,name) select 2,'mysql manual where no exists' from dual where not exists (select id from tab_mysqlinsert_tets where id = 2);select * from tab_mysqlinsert_tets;



0 0