MySql表插入,如果不存在,否则更新 [英] MySql Table Insert if not exist otherwise update

查看:104
本文介绍了MySql表插入,如果不存在,否则更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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表插入,如果不存在,否则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆