简体   繁体   English

基于非唯一键的UPDATE / INSERT?

[英]UPDATE/INSERT based on non-unique keys?

I have a table that contains 我有一张桌子,包含

id | user | date | data1 | data2 ......

where id is the primary unique key. 其中id是主唯一键。

I'm trying to write a query that can UPDATE if both user and date exist while INSERT if either one of them doesn't exist 我正在尝试编写一个查询,如果userdate存在,则可以date ,而如果其中一个都不存在,则可以插入。

I thought about the INSERT INTO...ON DUPLICATE KEY...UPDATE method, but that requires using the unique key, which I do have but not using. 我想到了INSERT INTO ... ON DUPLICATE KEY ... UPDATE方法,但这需要使用唯一的键,但我确实没有使用过。

What would be a good way to deal with this issue? 什么是处理此问题的好方法?

Per discussion in comments, you should make (user, date) a unique key. 根据评论中的讨论,您应该(user, date)为唯一键。

This will trigger the INSERT INTO ... ON DUPLICATE KEY UPDATE query as expected, updating rows with matching user and date fields, and inserting new ones where no match is found. 这将按预期触发INSERT INTO ... ON DUPLICATE KEY UPDATE查询,使用匹配的userdate字段更新行,并在找不到匹配项的地方插入新行。

The only valid option is to implement this UPSERT in the programming language that you use with mysql, because MySQL needs a unique key for both INSERT ... INTO and REPLACE . 唯一有效的选择是以与mysql一起使用的编程语言来实现此UPSERT ,因为MySQL INSERT ... INTOREPLACE都需要唯一的密钥。

Or to add a unique index on the user and date columns which seems to be in concordance with your business logic anyway. 或者在userdate列上添加唯一索引,该索引无论如何似乎都与您的业务逻辑相一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM