英文:
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');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论