MySQL replace into usage detailed introduction

Source: Internet
Author: User
MySQL Replace into usage (insert into enhanced version) is often encountered when inserting data into a table: 1. First, determine whether the data exists; 2. If it does not exist, then insert; 3. If present, update. This can be handled in SQL Server:   if not EXISTS (select 1 from t where id = 1)      inserts into T (ID, Update_time) VALUES (1, Getdat E ())   else      update t Set update_time = GETDATE () where id = 1 So how do you implement such logic in MySQL? Don't worry! There is an easier way to do this in MySQL: replace Intoreplace into t (ID, Update_time) VALUES (1, now ()), or replace into t (ID, update_time) Select 1, no W (); Replace into is similar to insert, except that replace into first attempts to insert data into the table, 1. If you find that this row of data is already in the table (judging by a primary key or a unique index), the row data is first deleted and then the new data is inserted. 2. Otherwise, insert the new data directly. Note that the table in which the data is inserted must have a primary key or a unique index! Otherwise, replace into will insert the data directly, which will result in duplicate data appearing in the table. MySQL replace into has three different forms: 1. Replace into Tbl_name (col_name, ...) VALUES (...) 2. Replace into Tbl_name (col_name, ...) Select ... 3. Replace into tbl_name set Col_name=value, ... The first two forms are used more. The "into" keyword can be omitted, but it is better to add "into" so that the meaning is more intuitive. In addition, for columns that are not given a value, MySQL automatically assigns default values to those columns.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.