文章目录 一、前言二、insert into … on duplicate key update ...1、处理逻辑2、示例:表结构1> 不存在记录,插入的情况2> 存在记录,可以更新字段的情况3> 存在记录,不可以更新字段的情况4
在日常开发中,经常会遇到这样的需求:查看某条记录是否存在,不存在的话创建一条新记录,存在的话更新某些字段。
比如下列伪代码:
$row = Mysql_query($result);if($row){mysql_execute('update ...');}else{mysql_execute('insert ...');}
MySql针对此,提供了insert into … on duplicate key update …的语法:
注意:这个是MYSQL特有的,不是SQL标准语法;
insert into … on duplicate key update …语句是根据唯一索引判断记录是否重复的;
如果表同时存在多个唯一索引,只会根据第一个在数据库中存在相应value的唯一索引做duplicate判断:
CREATE TABLE `user2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(94) NOT NULL, `age` int(11) DEFAULT NULL, `gender` int(1) DEFAULT NULL, `type` int(1) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `idex_name` (`userName`) USING BTREE, KEY `idx_type` (`type`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
user2表中有一个主键id、一个唯一索引idx_userName;
insert into user2(userName, age, gender) VALUES("saint33", 99, 1) on DUPLICATE KEY UPDATE age = 88;
insert into user2(userName, age, gender) VALUES("saint33", 99, 1) on DUPLICATE KEY UPDATE age = 88;
insert into user2(userName, age, gender) VALUES("saint33", 99, 1) on DUPLICATE KEY UPDATE age = 88;
如果表同时存在多个唯一索引,只会根据第一个在数据库中存在相应value的唯一索引做duplicate判断:
insert into user2(id, userName, age, gender) VALUES(12, "saint22", 99, 1) on DUPLICATE KEY UPDATE age = VALUES(gender) + 80;
insert into user2(id, userName, age, gender) VALUES(10, "saint22", 99, 1) on DUPLICATE KEY UPDATE age = VALUES(gender) + 90;
Update子句可以使用values(col_name)获取insert部分的值:
insert into user2(userName, age, gender) VALUES("saint22", 99, 1) on DUPLICATE KEY UPDATE age = VALUES(age) + 100;
注意:VALUES()函数只在INSERT…UPDATE语句中有意义,其它时候会返回NULL;
如果表含有auto_increment字段,使用insert … on duplicate key update插入或更新后,last_insert_id()返回auto_increment字段的值。
来源地址:https://blog.csdn.net/Saintmm/article/details/127444881
--结束END--
本文标题: mysql特殊语法insert into .. on duplicate key update ..使用详解
本文链接: https://www.lsjlt.com/news/373214.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0