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.