MySql: 仅在重复行不存在时创建行。

huangapple go评论48阅读模式
英文:

MySql: Create row only if duplicate row does not exist?

问题

我有一个名为firebaseTokens的表格,其中包含userId和tokenValue两列。当用户登录时,我的ReactJS前端获取设备令牌并将其分配给已登录用户的userId列。一个用户可能有多个令牌,一个令牌可能对应多个用户 - 因此userId列和tokenValue列都不能成为主键。我希望我的INSERT查询能检查是否存在重复的行,即userId=11和tokenValue=123456。如果已经存在与INSERT查询匹配的userId/tokenValue行,则不创建新行。但如果不存在这样的行,则插入新行。请问正确的语法是什么?

英文:

I have table firebaseTokens with columns userId and tokenValue. When a user logs in, my ReactJS frontend grabs the device token and assigns it to the logged in user via the userId column. A user may have many tokens, and a token may have many users - so neither userId column not tokenValue can be a primary key. I want my INSERT query to check for a duplicate row, i.e. userId=11 and tokenValue=123456. If a userId/tokenValue row matching the INSERT query already exists, then no new row is created. But if no such row already exists, then INSERT the row. What is the proper syntax for this?

答案1

得分: 1

Sure, here is the translated code part without the comments:

另外,关于 @stu 提到的,看一下这个:[MySQL INSERT IGNORE][1]

INSERT IGNORE INTO firebaseTokens (userId, tokenValue)
VALUES (11, '123456');

[1]: https://www.mysqltutorial.org/mysql-insert-ignore/
英文:

In addition on what @stu mention, look at this: MySQL INSERT IGNORE

INSERT IGNORE INTO firebaseTokens (userId, tokenValue)
VALUES (11, '123456');

答案2

得分: 1

你可以使用 REPLACE INTO 来在不存在时插入并在已存在时更新,前提是你拥有 (userId, tokenValue) 作为复合唯一索引,正如 Stu 所提到的:

REPLACE INTO firebaseTokens (userId, tokenValue)
VALUES (11, '123456');

演示在这里

英文:

You can use REPLACE INTO to Insert if not exist and update if exists, only if you have (userId, tokenValue) as a composite unique index as mentioned by Stu:

REPLACE INTO firebaseTokens (userId, tokenValue)
VALUES (11, '123456');

Demo here

huangapple
  • 本文由 发表于 2023年4月11日 06:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定