• insert into


    一.insert into批量插入数据

    需要对数据进行插表操作,由于数据量较大,按照一般的insert into将会有for循环操作,但如果产品流量大,对性能要求高,就选择批量插入。
    最终选择批量SQL过程如下:
    之前使用:
    insert into user_info (user_id,user_name,status,years)values (123,'你好',1,15);
    或者:
    insert into user_info set user_id=123,user_name=“你好”,status=1,years=15;
    这样的单句SQL插入,即使批量,也是循环进行。
    然后使用:
    insert into user_info (user_id,user_name,status,years)values (123,'你好',1,15),(456,"你好",2,16);可以插入多行。

    当在项目中插表操作时,可能并不知道所插的数据是否已经在表中,是不是会出现唯一索引冲突的情况,这些都是在批量插入时需要考虑的;
    这正是ON DUPLICATE KEY UPDATE和REPLACE的用武之地:
    ON DUPLICATE KEY UPDATE:如果插入行出现唯一索引或者主键重复时,则执行旧的update;如果不会导致唯一索引或者主键重复时,就直接添加新行。
    REPLACE:如果插入行出现唯一索引或者主键重复时,则delete老记录,而录入新的记录;如果不会导致唯一索引或者主键重复时,就直接添加新行。
    比较:
    1、在没有主键或者唯一索引重复时,replace与insert on deplicate udpate相同。
    2、在主键或者唯一索引重复时,replace是delete老记录,而录入新的记录,所以原有的所有记录会被清除,这个时候,如果replace语句的字段不全的话,有些原有的字段的值会被自动填充为默认值。
    如果以user_id 为主键,则:insert into user_info (user_id,user_name,status,years)values (123,'你好',1,15)on duplicate update user_name =values(user_name);
    此时,当user_id冲突时 ,将会保持主键不变,更改user_name,其他数据项操持原数据。
    replace into user_info (user_id,user_name,status,years)values (123,'你好',1,15);
    此时,(into 可省略)当user_id冲突时 ,将会删除原数据,新加数据项;

    注意:
    duplicate update则只执行update标记之后的sql,它保留了所有字段的旧值,只更新update后面的语句;
    而replace没有保留旧值,直接删除再insert新值,原有的所有记录会被清除,如果replace语句的字段不全的话,有些原有的字段的值会被自动填充为默认值。
    使用的时候结合场景选择。

    二.insert into 和select 结合使用

    1.语法
    insert into 新建表名 (新建表的字段1,字段2,字段3 ······)
    select 字段1,字段2,字段3 ······

    2.例子

    insert into newtb (district,districtid,town,townid,village,villageid)
    select infotb.district,infotb.districtid,infotb.town,infotb.townid,infotb.village,dictionary.villageid
    from infotb,dictionary
    where infotb.village like dictionary.village and infotb.town like dictionary.town and infotb.districtid like dictionary.districtid;
    
  • 相关阅读:
    guid与Base64编码互相转换
    xml序列化与反序列化工具
    Win10 15063 开始运行不保存历史记录原因和解决方法
    win10 localhost 解析为 ipv6地址 ::1 的解决办法
    在VisualStudio中应该使用什么字体
    S7-200系列PLC与WINCC以太网通信CP243i的实例
    超棒的 15 款 Bootstrap UI 编辑器
    NuGet学习笔记(转)
    SQLServer公历转农历函数(1900年-2049年)
    WPF 的datagrid 列名中没有显示下划线是怎么回事?
  • 原文地址:https://www.cnblogs.com/xidian2014/p/13653227.html
Copyright © 2020-2023  润新知