简体   繁体   English

MySQL 如果行存在则更新否则插入

[英]MySQL if row exists update else insert

I'm trying to make a site where people can sign up for events + an activity assigned to that event.我正在尝试创建一个网站,人们可以在其中注册活动 + 分配给该活动的活动。 They can choose which one they want to attend, or even both.他们可以选择参加哪一个,甚至两者都参加。

For that I made a table named "eventCounter" Image of table为此,我制作了一个名为“eventCounter”的表
userID, eventID and activityID are all FK poiting to other tables. userID、eventID 和 activityID 都是 FK 指向其他表。

They should be able to update their current "status", so they can join the activity after they signed up for the event.他们应该能够更新他们当前的“状态”,这样他们就可以在报名参加活动后加入活动。

So my question is: How can I make a If else saying if row exists update else insert所以我的问题是:我怎样才能做一个If else说 if row exists update else insert

 IF EXISTS(select userID, eventID, activityID from eventCounter where userID=1 and eventID=1) THEN UPDATE eventcounter SET activityID=1 WHERE userID=1; ELSE INSERT INTO eventcounter (userID, activityID) VALUES(1,1)

I don't think the ON DUPLICATE key will work as I have 2 columns that needs to be checked?我不认为 ON DUPLICATE 键会起作用,因为我有 2 列需要检查?

That's what is called an Upsert .这就是所谓的Upsert The MySQL syntax is pretty weird, but you can do it, something like: MySQL 的语法很奇怪,但你可以做到,例如:

INSERT INTO eventcounter (userID, eventID, activityID) VALUES(1,1,1)
ON DUPLICATE KEY UPDATE
  activityID = VALUES(activityID)

It only works for duplicate PKs though (not for any field you like), so in this case it would only work if userID and eventID compose the PK and you only want to change the activityID它仅适用于重复的 PK(不适用于您喜欢的任何字段),因此在这种情况下,它仅适用于userIDeventID组成 PK 并且您只想更改activityID eventID

Otherwise, you could go the IF-ELSE route, something like:否则,您可以走 IF-ELSE 路线,例如:

DECLARE mycount INT;
SET mycount = (SELECT COUNT(*) FROM eventcounter WHERE userID=1 AND eventID=1);
IF mycount > 0 THEN
  UPDATE eventcounter SET activityID=1 WHERE userID=1 AND eventID=1;
ELSE
  INSERT INTO eventcounter (userID, eventID, activityID) VALUES(1,1,1);
END IF;

Disclaimer: totally untested code免责声明:完全未经测试的代码

As 2021, things changed!到了 2021 年,事情发生了变化! So i'm updating the old @Jcl 's answer:所以我正在更新旧的@Jcl的答案:

One thing you have to bear in mind is that this statement only works if a duplication occurs either to PRIMARY KEY or UNIQUE INDEX in case of inserting ( so not only PK but index also works )!您必须记住的一件事是,此语句仅在插入时PRIMARY KEYUNIQUE INDEX发生重复时才有效(因此不仅PK而且index也有效)!


SQL command:

INSERT INTO fooTable (RowNum, name, lastname, userID, score) VALUES(3,'Michael','Widenius','1012141618',19.75)
ON DUPLICATE KEY UPDATE name = 'Allan', lastname = 'Larsson', userNum = '2022242628', score = 10.50;

Note:笔记:

  • The use of VALUES() to refer to the new row and columns is deprecated (Reference)不推荐使用VALUES()来引用新的行和列(参考)
  • Command tested on latest MYSQL 8.0 and PHP Mysqli too.命令也在最新的MYSQL 8.0PHP Mysqli上进行了测试。
  • Command above is only to show you, how to update multiple rows ;上面的命令只是告诉你,如何更新多行 in a real world situation, mostly you don't need to update all name , lastname and userID in case that record is already exist and score would be enough!在现实世界的情况下,大多数情况下您不需要更新所有namelastnameuserID ,以防记录已经存在并且score就足够了!

I found it pretty straight and easy to perform, you can check duplication on almost every important field in your case (using UNIQUE INDEX s )!我发现它非常直接且易于执行,您可以检查您案例中几乎每个重要字段的重复(使用UNIQUE INDEX s )! just remember the very first line...只记得第一行...

Alternatively, if anyone looking for a single query statement without any extra process to create an array to set the values, can try this query method.或者,如果有人在寻找没有任何额外过程来创建数组来设置值的单个查询语句,可以尝试这种查询方法。 This is just an improvement over @Shahaboddin's answer.这只是对@Shahaboddin's回答的改进。

INSERT INTO eventcounter 
    (
    userID,
    activityID
    )
SELECT userID, activityID FROM eventCounter WHERE userID=1 and eventID=1
ON DUPLICATE KEY UPDATE 
    userID = VALUES(userID),
    activityID = VALUES(activityID);

Note:笔记:

  • Tested on MySQL 5.6测试于 MySQL 5.6

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

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