Reputation: 19445
I have users from many external sources which I try to map to internal userId, so the table I have is:
userId, externalSourceId, externalUserId
In my code, I'm getting externalSourceId
and externalUserId
and want to get the userId
from the database, if exists, otherwise, create one and return the newly created value. I need this action to be atomic because several processes may try to do the same thing at the same time, so I wished only the first time will create a userId
.
In pseudo code it will look like that:
Upvotes: 0
Views: 78
Reputation: 519
INSERT IGNORE INTO test (externalSourceId
,externalUserId
) VALUES (23,32);
SELECT userId
FROM test WHERE externalSourceId
=23 AND externalUserId
=32;
You can use this if externalSourceId and externalUserId are defined unique.
Upvotes: 1
Reputation: 7282
INSERT INTO `users`
(`externalSourceId`, externalUserId)
VALUES( 10, 100)
ON DUPLICATE KEY
UPDATE userId=userId
You can also use insert ignore
. You can read more about DUPLICATE KEY versus INSERT IGNORE
Upvotes: 1