Home > Database > Mysql Tutorial > body text

MySQL中ONDUPLICATEKEYUPDATE使用_MySQL

WBOY
Release: 2016-06-01 13:13:25
Original
1276 people have browsed it

今天做判断插入用到了MySQL中ON DUPLICATE KEY UPDATE,现在Mark以下!

如果你想做到数据库中没有数据的话插入数据、有数据的话更新数据,那么你可以选择ON DUPLICATE KEY UPDATE。

ON DUPLICATE KEY UPDATE能够在UNIQUE索引或PRIMARY KEY存在的情况下对旧行执行UPDATE操作。

例如:如果列a被定义为UNIQUE,并且包含值1,则以下两个语句具有相同的效果:

      INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c = c + 1,b = b - 1;
Copy after login
      UPDATE table SET c = c + 1,b = b - 1 WHERE a = 1;
Copy after login

例如:如果INSERT多行记录(假设 a 为主键或 a 是一个 UNIQUE索引列):

      INSERT INTO TABLE (a,c) VALUES (1,3),(1,7) ON DUPLICATE KEY UPDATE c = c + 1;
Copy after login

执行后,c 的值会变为 4 (第二条与第一条重复, c 在原值上+1)。

      INSERT INTO TABLE (a,c) VALUES (1,3),(1,7) ON DUPLICATE KEY UPDATE c = VALUES(c);
Copy after login

执行后,c 的值会变为 7 (第二条与第一条重复, c 在直接取重复的值7)。

注意:ON DUPLICATE KEY UPDATE只是MySQL的特有语法,并不是SQL标准语法!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!