MYSQL various syntax features Detailed inserted or modified (replace into / insert ignore into / insert into on duplicate key update)

In our usual business scenario, there may be a lot of time, need to be increased or modify library operation (corresponding data lines already exist) (corresponding rows of data does not exist), this time, someone will think no matter what language, I will check there is no corresponding library data on this line, and then operate according to the results, do not get away with it (the existing data is modified, no data is added).

Solutions can think is good, but this, add or change after the first check of the program, there is a serious shortcoming, for the following reasons:

        1, you first check after the operation, this is not atomic, when multiple threads to operate, such as thread 1 and thread 2 have not queried this result, and then successively insert operation, if the library has done business the only constraint data, this situation will complain. will bring a variety of thread safety issues. perhaps you will think, thread-safety issues, it does not get away with locking nest yet? lock is of course possible, but this performance loss, for some business scenarios for high concurrency, some more harm than good.

        2, first check after the operation, the cost of this investigation, if the target table is in the order of millions and data level, this query results, not necessarily soon be able to return a result (in particular the case of a string index) when the network delay between the interface if you call this a relatively high frequency, not only IO load on the database, or the responsiveness of the interface, and multiple database requests is concerned, it is not a small overhead. and this time-consuming inquiry , will enlarge a security thread talking about.

A, replace into
the first on the construction of the table statement

CREATE TABLE `student` (
  `id` bigint(22) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键自增id',
  `student_id`            bigint(22) NOT NULL DEFAULT '0' COMMENT '学生id',
  `chinese_socre`       decimal(18,6) NOT NULL DEFAULT '0.000000' COMMENT '语文分数',
  `math_score`           decimal(18,6) NOT NULL DEFAULT '0.000000' COMMENT '数学分数',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `un_idx_stu_id` (`student_id`) USING BTREE

) ENGINE = InnoDB DEFAULT CHARSET = utf8 COMMENT = 'Students' table';

Scene:
    a grade language and math test make-up (performance data already exists some students, but may for some reason, some students are secondary examination (pre-existing data), and some because something did not come last exam (make-up is his first test, the original data does not exist)) is completed, this time replace into the syntax comes in handy,

replace into student(student_id,chinese_socre,math_score) values(1,58,59),(2,60,61),(3,62,63).......;

    Advantages
        1, simple syntax, but covering a wide situation:

                    For the second test of the students, this is first inserted into the data will overwrite the original data that is updated to the make-up of his latest score data (here, for the time being is not considered as a demanding production environment, you may need to retain its history scores scene)

                    For the first examination of the students, this time that is all it will insert new data

                    For students who do not need to participate in make-up, this time operation, its original data is not affected.
        2, because the database is the only index used to do business constraints, both to ensure the uniqueness of the final data, but also the first check after than before mode of operation to greatly improve the efficiency of (the absence of multiple network calls communication cost, uniqueness and to ensure efficient database queries by the unique indexes, etc.)

    Note:
    1, inserted in the data table must have a primary key or a unique index! Otherwise, replace into directly insert data, which will lead to duplicate data appear in the table

    2, if the data in the original table already exists (according to the primary key index to determine whether or not there), there is the update (delete the original, the new back), does not exist, add, replace into doing the whole amount update (complete with new data prevail, the original data is not saved)

    Business scenario analogy:
        for example, there are now two systems require docking, product data synchronization, the system is the output side A, B system is the receiver, the data A given is complete, the whole amount, and this time, you can using this grammar, B system does not need to consider a system for over product information, in the end is already existing, or previously had, need to be updated. the syntax is simple and multi-covering.

二、insert ignore into
        insert ignore into student(student_id,chinese_score,math_score) values(1,58,59),(2,60,61),(3,62,63).......;
        

    Scene, the advantages
        1, for example, was originally only a fraction of the data entry part of the students, then was accidentally interrupted, but has not resolved some of which are entered, then you can use this syntax, the original data does not affect (not because it has been a unique index duplicate data entry and error leads to interruption), but the data will be inserted on the new                    

        2, the database is the use of a unique index because of constraints of doing business, both to ensure the uniqueness of the final data, but also the way than before the first check after the operation efficiency is greatly improved (multiple communications network call costs do not exist, by the uniqueness The only index to ensure efficient database and query, etc.)

    Note:
    1, inserted in the data table must have a primary key or a unique index! Otherwise, insert ignore into directly insert data, which will lead to duplicate data appear in the table

    2, if the original data table already exists (primary key index is determined whether or not there), there is not any operation, does not exist, add, insert ignore into do is insert case increment (the original data exists overlap, It will be subject to the original data)

    Business scenario analogy:
        for example, there are now two systems require docking, order data synchronization, the receiver system and do some relevant statistics based on the success of each new orders data synchronization

        A solution is to do real-time synchronization system for B system, in order to avoid a certain period of time or a particular real-time synchronous exceptions, the evening will be the amount of time to do a full synchronization, this time, you can use this grammar, the system does not need to think about A B the order information system to come in the end is already occurring or not, with this syntax is compatible with both cases and insert, new returns the number of rows according to their impact can be determined in the end is to add a few single (combination of mybatis java framework, successful insertion can return increment primary key in the end is to determine which of these new single successful, to perform the respective subsequent traffic statistics calculation logic)

三、insert into    on duplicate keyupdate
    insert into student(student_id,chinese_score,math_socre) values(1,58,59),(2,60,61),(3,62,63).......  on duplicate key update chinese_socre = values(chinese_score),math_socre = math_socre;

    Scene, advantages
           such as the make-up, make-up just language, no math test. Such a grammar can be adopted, updated custom (existing data, that is, make-up)

        1, the syntax is simple, but covering a wide situation:

                    For example, the examination, if the students are participating in the second, only to update its language achievement, mathematics achievement or to maintain the original data

                    For the first examination of the students, this time that is all it will insert new data

                    For students who do not need to participate in make-up, this time operation, its original data is not affected.
        2, because the database is the only index used to do business constraints, both to ensure the uniqueness of the final data, but also the first check after than before mode of operation to greatly improve the efficiency of (the absence of multiple network calls communication cost, uniqueness and to ensure efficient database queries by the unique indexes, etc.)

        
Note:
    1, inserted in the data table must have a primary key or a unique index! Otherwise, this syntax directly into the data, which will lead to duplicate data appear in the table

    2, if the original data table already exists (primary key index is determined whether or not present), the presence of updating after the custom actions on duplicate key update, the new absence, he did the whole amount of the insert or update custom

    Business scenario analogy:
        for example, now has two docking systems require data synchronization product (assuming that A system where only commodity price data change occurs, others are not, the above example is all the attribute data of goods, attention the difference)

        A system to do real-time synchronization program is to system B, this time, you can use this grammar, B system does not need to consider A system of product information to come in the end is already occurring or not, with this syntax compatible insert two case and the emergence of this situation existing product data, update it only price information, reduce database overhead also operate after the update can be complex extended to provide custom operations support space syntax
------ ----------
Disclaimer: this article is the original article CSDN bloggers "not eternal", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/qq_18406563/article/details/80639029

Guess you like

Origin www.cnblogs.com/hsz1124/p/11641515.html