mysql一些insert/update的用法
在mysql中进行条件插入数据时,可能会用到以下语句,现小结一下。我们先建一个简单的表来作为测试:
1
2
3
4
5
6
7
8
9
10
11
create table `books` (
`id` int(11) not null auto_increment,
`name` varchar(200) not null,
primary key (`id`),
unique key `newindex1` (`name`)
) engine=innodb default charset=utf8;
1.insert ignore into
当插入数据时,如出现错误时,如重复数据,将不返回错误,只以警告形式返回。所以使用ignore请确保语句本身没有问题,否则也会被忽略掉。例如:
1
insert ignore into books (name) values (mysql manual)
2.on duplicate key update
当primary或者unique重复时,则执行update语句,如update后为无用语句,如id=id,则同1功能相同,但错误不会被忽略掉。例如,为了实现name重复的数据插入不报错,可使用一下语句:
1
insert into books (name) values (mysql manual) on duplicate key update id = id
3.insert … select … where not exist
根据select的条件判断是否插入,可以不光通过primary 和unique来判断,也可通过其它条件。例如:
1
insert into books (name) select mysql manual from dual where not exists (select id from books where id = 1)
4.replace into
如果存在primary or unique相同的记录,则先删除掉。再插入新记录。
1
replace into books select 1, mysql manual from books
网站建设效果应该注意的问题高端网站设计 为什么离不开沟通营销型网站具备的主要特征有哪些什么是页面活跃度?极简设计不仅好看,还能显著减少网站跳出率-佛山网站设计佛山网站建设公司我们该怎样在网站建设中设计关键词网站设计中的排版与配色如何搭配自如你们公司网站建设是怎么收费的?