问题描述
UPDATE AggregatedData SET datenum="734152.979166667",
Timestamp="2010-01-14 23:30:00.000" WHERE datenum="734152.979166667";
如果 datenum
存在,它可以工作,但如果 datenum
不存在,我想将此数据作为新行插入.
It works if the datenum
exists, but I want to insert this data as a new row if the datenum
does not exist.
更新
datenum 是唯一的,但它不是主键
the datenum is unique but that's not the primary key
推荐答案
Jai 是正确的,你应该使用 INSERT ... ON DUPLICATE KEY UPDATE
.
Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE
.
请注意,您不需要在 update 子句中包含 datenum,因为它是唯一键,因此不应更改.您确实需要包括表中的所有其他列.您可以使用 VALUES()
函数确保在更新其他列时使用正确的值.
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.
这是使用 MySQL 的正确 INSERT ... ON DUPLICATE KEY UPDATE
语法重写的更新:
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)
这篇关于MySql 表插入,如果不存在,否则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!