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

查看:48
本文介绍了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.

请注意,您不需要在更新子句中包含 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天全站免登陆