简体   繁体   English

检查 MySQL 条目是否存在,如果存在,则覆盖其他列

[英]Check if MySQL entry exists, if it does, overwrite other columns

I have a MySQL table set out as the following我有一个 MySQL 表,如下所示

UID | Thing1 | Thing2 | Date

The UID column has been set as unique and is made from the users ID + the date as an integer. UID 列已设置为唯一且由用户 ID + 日期作为整数组成。 IE 7620150715 IE 7620150715

What I'd like to do is check to see if the UID exists, if it does, then update columns thing1 and thing2 with the latest information.我想要做的是检查 UID 是否存在,如果存在,则使用最新信息更新 thing1 和 thing2 列。

If the UID doesn't exist, then create a new row for all the information.如果 UID 不存在,则为所有信息创建一个新行。

Currently, what works to enter is目前,可以进入的是

$sql = "INSERT INTO things2 (uid, thing1, thing2, date) VALUES (:uid, :thing1,:thing2,:date)";

But this doesn't work after making UID unique.但这在使 UID 唯一后不起作用。

I've found that the ON DUPLICATE KEY UPDATE statement seems to be what I'm looking for, but all answers appear to be adding +1 to the input, which is not what I want to do.我发现 ON DUPLICATE KEY UPDATE 语句似乎是我正在寻找的,但所有答案似乎都在输入中添加 +1,这不是我想要做的。

Some pseudo syntax for what I'm looking for would go like this我正在寻找的一些伪语法会像这样

$sql = "INSERT INTO things2 (uid, thing1, thing2, date) VALUES (:uid, :thing1,:thing2,:date ON DUPLICATE KEY UPDATE (thing1, thing2) VALUES (:thing1, :thing2)";

What would be the correct syntax?什么是正确的语法?

The easiest/most clear way needs two steps:最简单/最清晰的方法需要两个步骤:

First do an INSERT OR IGNORE of just the (new) UID.首先只对(新)UID 执行 INSERT OR IGNORE。 Don't bother with the values yet, because you will update anyway.暂时不要理会这些值,因为无论如何您都会更新。 Just make sure that table allows this with proper defaults and not too many constraints:只需确保该表允许使用适当的默认值并且没有太多约束:

INSERT OR IGNORE INTO things2 (uid) VALUES (:uid)

Then do an UPDATE ... SET a=b WHERE UID=.. to actually update the records:然后执行 UPDATE ... SET a=b WHERE UID=.. 以实际更新记录:

UPDATE thing1=:thing1, thing2=:thing2 WHERE UID = :uid

(Not tested, and please check because I am more into C++/sqlite than in MySql/php) (未测试,请检查,因为我更喜欢 C++/sqlite 而不是 MySql/php)

Your syntax is a little wrong.你的语法有点错误。 If the INSERT fails then you code an UPDATE with the standard UPDATE syntax like so.如果 INSERT 失败,那么您可以使用标准的 UPDATE 语法编写 UPDATE 代码,如下所示。

$sql = "INSERT INTO things2 
               (uid, thing1, thing2, `date`) 
        VALUES (:uid, :thing1,:thing2,:date )
        ON DUPLICATE KEY 
        UPDATE things2 SET thing1 = :thing1, thing2 = :thing2, `date` = :date";

Also date is a reserved word so its best to wrap it in backticks. date也是一个保留字,所以最好用反引号把它包起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM