Home > Database > Mysql Tutorial > ON DUPLICATE KEY UPDATE注意事项_MySQL

ON DUPLICATE KEY UPDATE注意事项_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:55:06
Original
1202 people have browsed it

MySQL 自4.1版以后开始支持INSERT … ON DUPLICATE KEY UPDATE语法,使得原本需要执行3条SQL语句(SELECT,INSERT,UPDATE),缩减为1条语句即可完成。

例如ipstats表结构如下:

引用

CREATE TABLE ipstats (
ip VARCHAR(15) NOT NULL UNIQUE,
clicks SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0'
);

原本需要执行3条SQL语句,如下:

IF (SELECT * FROM ipstats WHERE ip='192.168.0.1') {
 UPDATE ipstats SET clicks=clicks+1 WHERE ip='192.168.0.1';
} else {
 INSERT INTO ipstats (ip, clicks) VALUES ('192.168.0.1', 1);
}

而现在只需下面1条SQL语句即可完成:

INSERT INTO ipstats VALUES('192.168.0.1', 1) ON DUPLICATE KEY UPDATE clicks=clicks+1;

注意,要使用这条语句,前提条件是这个表必须有一个唯一索引或主键。

Related labels:
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