On the usage of Mysql replace into _mysql

Source: Internet
Author: User
Tags getdate

This can be done in SQL Server:

Copy Code code as follows:

If not exists (select 1 from t where id = 1)
INSERT into T (ID, Update_time) VALUES (1, GETDATE ())
Else
Update T Set update_time = GETDATE () Where id = 1

So how does MySQL implement such a logic? Don't worry! There is a simpler way to do this in MySQL: replace into

Copy Code code as follows:

Replace into t (ID, Update_time) VALUES (1, now ());
Or
Replace into t (ID, update_time) Select 1, now ();

The replace into is similar to the Insert feature, 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 (judged by a primary key or a unique index), the row data is deleted first, and then the new data is inserted. 2. Otherwise, insert the new data directly. Note that the table that inserts the data must have a primary key or a unique index! Otherwise, replace into inserts the data directly, which causes duplicate data to appear in the table.

There are three forms of MySQL replace into:

Copy Code code as follows:

Replace into Tbl_name (col_name, ...) VALUES (...)
Replace into Tbl_name (col_name, ...) Select ...
Replace into Tbl_name set Col_name=value, ...

The first two forms are used more. Where the "into" keyword can be omitted, but it is best to add "into", which means more intuitive. In addition, MySQL automatically assigns default values to columns that are not given values.

Related Article

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.