CREATE TABLE `subject` (
`subjectId` int NOT NULL AUTO_INCREMENT COMMENT '自增,科目编号',
`subjectName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '科目名称',
PRIMARY KEY (`subjectId`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '科目表' ROW_FORMAT = Dynamic;
1.存在就更新,不存在就新增
使用replace关键字,存在就更新,不存在就新增一条数据表必须有唯一索引unique,且索引所在字段值不能为空。replace into 'subject' (subjectId,subjectName)
values (1,'离散');
根据主键判断是否存在,执行新增(insert)或修改(update) *** 作;on duplicate keyupdate为mysql独有语法。
insert into `subject`(subjectId,subjectName)
values('7','离散')
on duplicate key update subjectName='离散数学';
2.存在则不 *** 作,不存在则新增
insert ignore,必须有唯一键unique。insert ignore 'subject'(subjectId,subjectName)
values (1,'离散');
使用insert…select…语句;使用 dual 做表名可以让你在 select语句后面直接跟上要插入字段的值,而且这些值还可以不存在当前表中。
INSERT INTO `subject`(subjectId,subjectName)
SELECT 2,'离散数学'
FROM dual
WHERE not exists (select subjectId,subjectName from `subject`
where subjectId='1' and subjectName='离散');
# 与主键无关
INSERT INTO `subject`(subjectName)
SELECT '离散数学'
FROM dual
WHERE not exists (select subjectName from `subject`
where subjectName='离散');
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)