MySQL's "insert" / "delete + insert" operation - REPLACE

Question and background:

There is a data table Table, the primary key is a string in the form of YYYY-MM-DD (year, month, day), which stores the information of a certain event on this day, and the information will be recalculated according to the latest data every few hours. If the record of this day already exists in the table, you need to perform "UPDATE" or "DELATE+INSERT" operation on it to update the event information of this day; if it is in the early morning, when the record of this day does not exist, you need to perform "INSERT" on the information.

According to the requirements, it is necessary to judge whether there is a record before inserting each time, which will lead to the complexity of programming.

Solution:

At this point, you can use the REPLACE operation. REPLACE works exactly the same as INSERT, except that if the old row in the table has the same index as the new row, the old row will be deleted before the new row is inserted. This is consistent with our desired result.

REPLACE using:

The usage of replace and insert is very similar, the following are two examples

REPLACE INTO 数据表(col_name1, col_name2, col_name3,......) VALUES ('value1', 'value2', 'value3', ......);
REPLACE INTO 数据表 VALUES ('value1', 'value2', 'value3', ......);

You can refer to:

REPLACE Statement

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    { {VALUES | VALUE} (value_list) [, (value_list)] ...
      |
      VALUES row_constructor_list
    }

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    SET assignment_list

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [(col_name [, col_name] ...)]
    {SELECT ... | TABLE table_name}

おすすめ

転載: blog.csdn.net/qq_44667259/article/details/123550908
おすすめ