Home > Database > Mysql Tutorial > MySQL中的insert ignore into, replace into等的一些用法总结_MySQL

MySQL中的insert ignore into, replace into等的一些用法总结_MySQL

WBOY
Release: 2016-06-01 13:45:34
Original
1183 people have browsed it

bitsCN.com

 

在MySQL中进行条件插入数据时,可能会用到以下语句,现小结一下。我们先建一个简单的表来作为测试:

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请确保语句本身没有问题,否则也会被忽略掉。例如:

INSERT IGNORE INTO books (name) VALUES ('MySQL Manual')

2.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

3.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)

4.replace into

如果存在primary or unique相同的记录,则先删除掉。再插入新记录。

REPLACE INTO books SELECT 1, 'MySQL Manual' FROM books

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template