UPDATE AggregatedData SET datenum="734152.979166667", Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";
It works if the datenum
exists, but I want to insert this data as a new row if the datenum
does not exist.
UPDATE
the datenum is unique but that's not the primary key
Often you have the situation that you need to check if an table entry exists, before you can make an update. If it does not exist, you have to do an insert first. Unfortunately, this the 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns.
The alternative (and generally preferred) method for INSERTING into rows that may contain duplicate UNIQUE or PRIMARY KEY values is to use the INSERT ... ON DUPLICATE KEY UPDATE statement and clause.
No. Insert will only create a new row.
We can perform MySQL UPSERT operation mainly in three ways, which are as follows: UPSERT using INSERT IGNORE. UPSERT using REPLACE. UPSERT using INSERT ON DUPLICATE KEY UPDATE.
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES()
function to make sure the proper values are used when updating the other columns.
Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE
syntax for MySQL:
INSERT INTO AggregatedData (datenum,Timestamp) VALUES ("734152.979166667","2010-01-14 23:30:00.000") ON DUPLICATE KEY UPDATE Timestamp=VALUES(Timestamp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With