草庐IT

MySql -- 不存在则插入,存在则更新或忽略

普通网友 2024-01-23 原文

1.前言

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语句,例:

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;

@Repository
public 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 mapper
PUBLIC "-//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;

@Service
public 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开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

有关MySql -- 不存在则插入,存在则更新或忽略的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  3. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  4. c - mkmf 在编译 C 扩展时忽略子文件夹中的文件 - 2

    我想这样组织C源代码:+/||___+ext||||___+native_extension||||___+lib||||||___(Sourcefilesarekeptinhere-maycontainsub-folders)||||___native_extension.c||___native_extension.h||___extconf.rb||___+lib||||___(Rubysourcecode)||___Rakefile我无法使此设置与mkmf一起正常工作。native_extension/lib中的文件(包含在native_extension.c中)将被完全忽略。

  5. ruby-on-rails - rspec - 如何检查方法是否存在? - 2

    我的模型有defself.empty_building//stuffend我怎样才能对这个现有的进行rspec?,已经尝试过:describe"empty_building"dosubject{Building.new}it{shouldrespond_to:empty_building}endbutgetting:Failure/Error:it{shouldrespond_to:empty_building}expected#torespondto:empty_building 最佳答案 你有一个类方法self.empty_bu

  6. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

  7. Ruby - 如何在读取文件时跳过/忽略特定行? - 2

    在读取/解析文件(使用Ruby)时忽略某些行的最佳方法是什么?我正在尝试仅解析Cucumber.feature文件中的场景,并希望跳过不以Scenario/Given/When/Then/And/But开头的行。下面的代码有效,但它很荒谬,所以我正在寻找一个聪明的解决方案:)File.open(file).each_linedo|line|line.chomp!nextifline.empty?nextifline.include?"#"nextifline.include?"Feature"nextifline.include?"Inorder"nextifline.include?

  8. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  9. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  10. ruby-on-rails - ActiveRecord 的 find_or_create* 方法是否存在根本性缺陷? - 2

    有几种方法:first_or_create_by、find_or_create_by等,它们的工作原理是:与数据库对话以尝试找到我们想要的东西如果我们找不到,就自己做保存到数据库显然,并发调用这些方法可能会使两个线程都找不到它们想要的东西,并且在第3步中一个线程会意外失败。似乎更好的解决方案是,创建或查找即:提前在您的数据库中创建合理的唯一性约束。如果你想保存一些东西,就保存它如果有效,那就太好了。如果它因为RecordNotUnique异常而无法工作,它已经存在,太好了,加载它那么在什么情况下我想使用Rails内置的东西而不是我自己的(看起来更可靠)create_or_find?

随机推荐