MySql Insert or Update Based on Unique Condition
Inserting data into a MySQL table often involves checking if the data already exists before performing an update. However, when dealing with unique non-primary key columns, the traditional UPDATE statement falls short.
In this case, the user seeks an efficient method to insert data into an AggregatedData table if the datenum column doesn't exist, or update the existing row if it does.
Solution: INSERT ... ON DUPLICATE KEY UPDATE
As suggested by Jai, the most suitable solution is to utilize the INSERT ... ON DUPLICATE KEY UPDATE syntax:
INSERT INTO AggregatedData (datenum,Timestamp) VALUES ("734152.979166667","2010-01-14 23:30:00.000") ON DUPLICATE KEY UPDATE Timestamp=VALUES(Timestamp)
This statement performs an insert if the datenum is not found. If it does exist, it updates the Timestamp column with the value provided in the VALUES() function.
Explanation
The VALUES() function ensures that the values used for the update are the same as those specified in the INSERT statement. This prevents accidental column value updates.
Advantages of INSERT ... ON DUPLICATE KEY UPDATE
The above is the detailed content of MySQL Insert or Update: How to Handle Unique Non-Primary Key Columns Efficiently?. For more information, please follow other related articles on the PHP Chinese website!