简体   繁体   English

如果存在则更新一行,否则插入

[英]Update a row if exists otherwise insert

I have a table 'match' like 我有一张像'匹配'的桌子

id|user1|user2|paired
--+-----+-----+--------+
1 |U_1  |null |false

I need to match a new user 'U_2' to a record where paired = false, or create a new entry in table if no unpaired row is found. 我需要将新用户'U_2'与配对= false的记录匹配,或者如果未找到未配对的行,则在表中创建新条目。

This db is connected to a server where multiple users might be trying to get paired, so I need to find best possible solution that makes it fast so it doesn't lock the table for long. 此数据库连接到多个用户可能尝试配对的服务器,因此我需要找到最快的解决方案,使其快速,因此它不会长时间锁定表。

the solution I came up with was 我想出的解决方案是

int matchId = select id from match where ((user1 != 'U_2') AND (paired = false));

if(matchId > 0)
then
   update table match set user2 = 'U_2' where id = matchId; 
else
   insert new row.

Please suggest a better way. 请建议一个更好的方法。

Thanks in advance. 提前致谢。

You can 您可以

  • add unique indices for user1 and user2 to improve speed and assure integrity. 为user1和user2添加唯一索引,以提高速度并确保完整性。
  • use Transaction to avoid collisions. 使用Transaction来避免冲突。
  • combine the select and update query in one update: 在一次更新中组合选择和更新查询:

     update table match set user2 = 'U_2' where ((user1 != 'U_2') AND (paired = false)) LIMIT 1; 
  • check if the update has affected rows . 检查更新是否影响了行 If not, insert the new row. 如果没有,请插入新行。

If i understand your intension properly, you can also: 如果我理解你的意图,你也可以:

  • remove the column paired , it seems to be redundant, since it is always false when user2=null 删除paired的列,似乎是多余的,因为当user2=null时它始终为false

A single statement does one or the other: 单个陈述可以做一个或另一个:

INSERT INTO match
    (user1, paired, user2)
    VALUES
    ('U_2', false, 'U_2')   -- either insert this
ON DUPLICATE KEY UPDATE
    user2 = VALUES(user2);  -- or update this

Together with 和...一起

PRIMARY KEY(user1, paired)  -- a UNIQUE key to control what is "DUPLICATE"

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

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