如何插入一行,但重复而不是更新它? [英] How to insert a row, but on duplicate; update it instead?

查看:59
本文介绍了如何插入一行,但重复而不是更新它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中包含游戏用户所拥有的物品.如果用户购买了新商品,则应插入新商品,但如果已经购买,则应增加新商品.

I have a table which contains the items the users of my game owns. If a user buys a new item, it should be inserted, but if he already got it, it should be increased instead.

我知道我可以使用INSERT ... ON DUPLICATE KEY UPDATE,但是我不知道如何解决问题.

I understand I can use INSERT ... ON DUPLICATE KEY UPDATE, but I don't understand how in my problem.

item_id不是唯一的,因为许多玩家可以拥有相同的武器(例如长剑). user_id也不是唯一的,因为玩家可以拥有许多物品.

The item_id isn't unique, because many players can own the same weapon (ie. a longsword). The user_id isn't unique either, because a player can own many items.

所以,我的问题是,如果同时包含user_iditem_id的行已经存在,如何进行查询UPDATE而不是INSERT?

So, my question is how to make the query UPDATE instead of INSERT if a row containing both the user_id and item_id already exists?

推荐答案

那不是"ON DUPLICATE KEY UPDATE"对您的作用.如果是我,我会尝试插入.如果失败,请检查原因(您正在检查错误,对吗?).如果是因为重复的密钥,请进行更新.如果错误是由于其他原因造成的,请适当地处理.

That's not what the "ON DUPLICATE KEY UPDATE" will do for you. If it were me, I would attempt the insert. If it failed, check why (you're checking for errors already, right?). If it's because of a duplicate key, do your update. If the error is for some other reason, then handle that appropriately.

这篇关于如何插入一行,但重复而不是更新它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆