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

时间:2016-11-30 22:48:41

标签: mysql sql

我有一张桌子'匹配'喜欢

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

我需要匹配新用户' U_2'到paired = false的记录,如果没有找到未配对的行,则在表中创建一个新条目。

此数据库连接到多个用户可能尝试配对的服务器,因此我需要找到最快的解决方案,使其快速,因此它不会长时间锁定表。

我提出的解决方案是

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.

请建议更好的方法。

提前致谢。

1 个答案:

答案 0 :(得分:3)

单个陈述可以做其中一个:

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

一起
PRIMARY KEY(user1, paired)  -- a UNIQUE key to control what is "DUPLICATE"
相关问题