位置: IT常识 - 正文

MySql -- 不存在则插入,存在则更新或忽略(mysql如果不存在就创建表)

编辑:rootadmin
MySql -- 不存在则插入,存在则更新或忽略 1.前言

推荐整理分享MySql -- 不存在则插入,存在则更新或忽略(mysql如果不存在就创建表),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:mysql表不存在则创建表,mysql不存在的数据类型,mysql不存在则创建表,mysql不存在则增加字段,mysql不存在查询,mysql不存在则新增,mysql不存在则创建表,mysql不存在则增加字段,内容如对您有帮助,希望把文章链接给更多的朋友!

Mysql在插入数据时,需要忽略或替换掉重复的数据(依据某个字段,比如Primary Key或

Unique Key来确定是否重复),这时候我们既可以在应用层处理,也可以使用复杂的 SQL 语句来处理(如果仅仅知道一些简单的 SQL 语法的话),当然也可以使用一些简单的 SQL 语法,不过它并不是通用所有的数据库类型。

下面我们以MySQL为例,研究一下insert 怎样去忽略或替换重复数据

2.表实例

表名称:person

表字段:

Column Name

Primary Key

Auto Increment

Unique

id

true

true

name

true

age

初始表数据:

id

name

age

111

Bruce

36

3.三个简单例子:

Note:本文的3个例子都需要被插入的表中存在UNIQUE索引或PRIMARY KEY字段

1. 不存在则插入,存在则更新1.1 on duplicate key update

如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则执行UPDATE语句,例:

MySql -- 不存在则插入,存在则更新或忽略(mysql如果不存在就创建表)

INSERT INTO `person`(`name`, `age`) VALUES(‘Bruce’, 18) ON DUPLICATE KEY UPDATE `age`=19; – If will happen conflict, the update statement is executed

– 2 row(s) affected

这里受影响的行数是2,因为数据库中存在name='Bruce'的数据,如果不存在此条数据,则受影响的行数为1。

最新的表数据如下:

id

name

age

1

Bruce

18

1.2 replace into

如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则先删除旧数据再插入最新的数据,例:

REPLACE INTO `person`(`name`, `age`) VALUES(‘Bruce’, 20);

– 2 row(s) affected

这里受影响的行数是2,因为数据库中存在name='Jack'的数据,并且id的值会变成2,因为它是先删除旧数据,然后再插入数据,最新的表数据如下:

id

name

age

2

Bruce

20

2. 避免重复插入(存在则忽略)

关键字/句:insert ignore into,如果插入的数据会导致UNIQUE索引或PRIMARY KEY发生冲突/重复,则忽略此次操作/不插入数据,例:

INSERT IGNORE INTO `person`(`name`, `age`) VALUES(‘Bruce’, 18);

– 0 row(s) affected

这里已经存在name='Bruce'的数据,所以会忽略掉新插入的数据,受影响行数为0,表数据不变。

4.三个复杂例子:

我们可以用customerMobile字段作为唯一索引(UNIQUE 索引)

Mapper类:

package com.example.springbootmybatisplusbruce.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.springbootmybatisplusbruce.model.E**Customer;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import java.util.List;@Repositorypublic interface E**CustomerMapper extends BaseMapper<E**Customer> { /** * 不存在则插入,存在则更新 * on duplicate key update: 如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则执行UPDATE语句 * @param e**Customer * @return */ public int insertDuplicateKeyUpdate(E**Customer e**Customer); /** * replace into: 如果插入的数据会导致UNIQUE索引 或 PRIMARY KEY 发生冲突/重复,则先删除旧数据,再插入最新的数据 * @param etcCustomer * @return */ public int insertReplaceInto(E**Customer e**Customer); /** * 避免重复插入 * insert ignore into: 如果插入的数据会导致UNIQUE索引或PRIMARY KEY发生冲突/重复,则忽略此次操作/不插入数据 * @param e**Customer * @return */ public int insertIgnore(E**Customer e**Customer);}

xml文件:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.springbootmybatisplusbruce.mapper.E**CustomerMapper"> <resultMap type="com.example.springbootmybatisplusbruce.model.E**Customer" id="E**CustomerResult"> <result property="id" column="id" /> <result property="customerType" column="customer_type" /> <result property="customerName" column="customer_name" /> <result property="customerMobile" column="customer_mobile" /> ....................................................................... </resultMap> <sql id="selectE**CustomerVo"> select id, customer_type, customer_name, customer_mobile,...........................................................................from etc_customer </sql> <!-- 不存在则插入,存在则更新 --> <!-- on duplicate key update: 如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则执行UPDATE语句 --> <insert id="insertDuplicateKeyUpdate" parameterType="com.example.springbootmybatisplusbruce.model.E**Customer"> INSERT INTO e**_customer(id, customer_type, customer_name, customer_mobile, credential_type, credential_no, status, del_flag, create_by, create_time, update_by, update_time, remark) VALUES(#{id}, #{customerType}, #{customerName}, #{customerMobile}, #{credentialType}, #{credentialNo}, #{status}, #{delFlag}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark}) ON DUPLICATE KEY UPDATE <if test="customerType != null">customer_type=#{customerType},</if> <if test="customerName != null and customerName != ''">customer_name=#{customerName},</if> <if test="customerMobile != null and customerMobile != ''">customer_mobile=#{customerMobile},</if> <if test="credentialType != null">credential_type=#{credentialType},</if> <if test="credentialNo != null and credentialNo != ''">credential_no=#{credentialNo},</if> <if test="status != null">status=#{status}</if> </insert> <!-- replace into: 如果插入的数据会导致UNIQUE索引 或 PRIMARY KEY 发生冲突/重复,则先删除旧数据再插入最新的数据 --> <insert id="insertReplaceInto"> REPLACE INTO e**_customer(id, customer_type, customer_name, customer_mobile, credential_type, credential_no, status, del_flag, create_by, create_time, update_by, update_time, remark) VALUES(#{id}, #{customerType}, #{customerName}, #{customerMobile}, #{credentialType}, #{credentialNo}, #{status}, #{delFlag}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark}) </insert> <!-- 避免重复插入 --> <!-- insert ignore into: 如果插入的数据会导致UNIQUE索引或PRIMARY KEY发生冲突/重复,则忽略此次操作/不插入数据 --> <insert id="insertIgnore"> INSERT IGNORE INTO e**_customer(id, customer_type, customer_name, customer_mobile, credential_type, credential_no, status, del_flag, create_by, create_time, update_by, update_time, remark) VALUES(#{id}, #{customerType}, #{customerName}, #{customerMobile}, #{credentialType}, #{credentialNo}, #{status}, #{delFlag}, #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{remark}) </insert></mapper>

service类:

package com.example.springbootmybatisplusbruce.service;import com.example.springbootmybatisplusbruce.mapper.ETCCustomerMapper;import com.example.springbootmybatisplusbruce.model.EtcCustomer;import org.apache.commons.io.FileUtils;import org.apache.commons.io.LineIterator;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.List;@Servicepublic class FTPFileParseService { @Autowired private E**CustomerMapper e**CustomerMapper; /** * 参考文章:https://blog.csdn.net/t894690230/article/details/77996355 * https://blog.csdn.net/weixin_45607513/article/details/117470118 * @throws IOException */ @Transactional(rollbackFor = Exception.class) public void fileParse() throws IOException { StringBuilder result = new StringBuilder(); String path = "F:\Digital marketing\E** system\txt-from-ftp\20210302_VEHICLE.txt"; long start = System.currentTimeMillis(); //程序执行前的时间戳 BufferedReader br = new BufferedReader(new FileReader(path));//构造一个BufferedReader类来读取文件 String line = null; while((line = br.readLine())!=null){//使用readLine方法,一次读一行// result.append(System.lineSeparator()+s); System.out.println("Debug:" + line); String [] infoArray = line.split("@~@"); EtcCustomer e**Customer = new EtcCustomer(); if(infoArray[0].isEmpty()){continue;} e**Customer.setId(Long.valueOf(infoArray[0]).longValue()); e**Customer.setCustomerType(Long.valueOf(infoArray[4]).longValue()); e**Customer.setCustomerName(infoArray[2]); e**Customer.setCustomerMobile(infoArray[3]); e**Customer.setCredentialType(Long.valueOf(infoArray[5]).longValue()); e**Customer.setCredentialNo(infoArray[6]); e**Customer.setStatus(Long.valueOf(infoArray[15]).longValue()); e**Customer.setDelFlag(0L); //on duplicate key update: 如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则执行UPDATE语句// e**CustomerMapper.insertDuplicateKeyUpdate(etcCustomer); //insert ignore into: 如果插入的数据会导致UNIQUE索引或PRIMARY KEY发生冲突/重复,则忽略此次操作/不插入数据 e**CustomerMapper.insertIgnore(etcCustomer); //replace into: 如果插入的数据会导致UNIQUE索引 或 PRIMARY KEY 发生冲突/重复,则先删除旧数据,再插入最新的数据// e**CustomerMapper.insertReplaceInto(etcCustomer); } br.close(); long end = System.currentTimeMillis(); //程序执行后的时间戳 System.out.println("程序执行花费时间:" + (end - start)); }}

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

本文链接地址:https://www.jiuchutong.com/zhishi/283499.html 转载请保留说明!

上一篇:最薄的平板电脑是什么(最薄的平板电脑是哪种)

下一篇:电脑硬盘跳线设置图解(硬盘跳线设置)

  • 进项留抵转出会计分录
  • 小微企业月开票超15万季度未超45万
  • 房地产开发产品科目
  • 住房补贴需要交什么材料
  • 自产和外购的视频区别
  • 换公司后个税app上没有显示缴费记录
  • 私车公用产生的过路费开个人发票还是公司发票
  • 用于不动产的进项税能抵扣吗
  • 公司股东变更麻烦吗?
  • 在建工程 费用
  • 将自建的厂房对外转让需要缴纳增值税吗
  • 所得税汇算有研发费用可以不享受加计扣除吗
  • 7.1发票没有税号怎么开
  • 个体户地税怎么收费
  • 机动车类专用发票
  • 开票资料上的电话可以是手机吗?
  • 存款保险能取出来钱吗
  • 国税地税合并后叫什么名称
  • 居民企业之间以非货币资产进行投资
  • 季度所得税报表怎么填
  • 资金筹集业务核算实训心得体会
  • 管理费用劳务费包括什么
  • 注册表修改系统安装日期
  • appdata如何移动
  • 农业公司的会计分录
  • 净利润与未分配利润的勾稽关系
  • linux zen3
  • 美团提现手续费入哪个会计科目
  • PHP:ftp_set_option()的用法_FTP函数
  • 长期借款的账务处理怎么做分录
  • ChatGLM-6B (介绍相关概念、基础环境搭建及部署)
  • php目录结构
  • 楼房贷款需要什么手续没有银行流水怎么办
  • 银行罚息可不可以扣除
  • 销售使用过的机器设备如何缴纳增值税
  • 收到承兑汇票怎么签收
  • 基建会计的工作内容
  • 前端 自动化脚本 怎么写
  • uniapp简介
  • 企业付检测费的会计科目
  • 命令行怎么管理员运行
  • 税控盘总是连接服务器失败
  • 社保滞纳金计入个人账户吗
  • 织梦cms要钱吗
  • 长期待摊费用是什么意思
  • SQL Server 2005/2008 导入导出数据常见报错解决方法
  • 待处理流动资产损失属于什么科目
  • 普通发票的税费计入应交税费吗
  • 让渡资产使用权包括
  • 给客户的客户开普票算不算虚开
  • 工会经费到底怎么算
  • 存货呆滞的原因及处理表格
  • 银行手续费发票未到怎样做账
  • 上个月结转的流量下个月能用吗
  • 外购材料的核算方法有
  • 商业承兑汇票结算会计分录
  • 塑料行业税负率是多少
  • 美国支票上的收款人地址不对怎么办
  • 企业如何科学设计产品
  • sql提取数据库表中的数据
  • sqlserver数据库版本号怎么查
  • win8.1升级win10系统
  • win8打开运行的快捷键是什么
  • win10错误提示
  • windows8使用教程
  • win10系统如何禁用u盘
  • win10周年版
  • windows7电脑无法正常运行
  • windows7 excel
  • opengl读取obj文件
  • linux终端命令行和输出在一行
  • nginx服务器日志
  • Node.js中的事件循环是什么样的
  • 什么是javascrip
  • javascript学习指南
  • 电子发票未验真是假发票吗
  • 如何查询个体工商户是查账征收还是核定征收
  • 外经证预缴税款网上流程
  • 山西电子税务局手机版
  • 租房减免税收
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设