Home >Database >Mysql Tutorial >How to Update or Insert into a MySQL Table Based on a Unique Key's Existence?
MySql Table Update or Insert if Unique Key Exists
In MySQL, you can insert a new row into a table if a specific unique key doesn't exist, or update an existing row if the key does exist. This can be achieved using the INSERT ... ON DUPLICATE KEY UPDATE statement.
To achieve the desired behavior for your scenario, you should modify your original query to an INSERT ... ON DUPLICATE KEY UPDATE statement. The ON DUPLICATE KEY UPDATE clause specifies what columns should be updated if the unique key already exists. In this case, you want to update the Timestamp column.
Here is the modified statement:
INSERT INTO AggregatedData (datenum, Timestamp) VALUES ("734152.979166667", "2010-01-14 23:30:00.000") ON DUPLICATE KEY UPDATE Timestamp = VALUES(Timestamp)
This statement will insert a new row with the specified datenum and Timestamp. If a row with the same datenum already exists, only the Timestamp will be updated with the new value.
The above is the detailed content of How to Update or Insert into a MySQL Table Based on a Unique Key's Existence?. For more information, please follow other related articles on the PHP Chinese website!