简体   繁体   English

如果满足两列(无论顺序)的条件,则INSERT或UPDATE

[英]INSERT or UPDATE if condition over two columns (regardless of order) is met

I want to do the following: 我想做以下事情:

INSERT INTO table1 (term1, term2, number) values ('A','B',10); 

however if values A and B are already present in table1 regardless of their order, ie. 但是,如果值1和B已经存在于表table1 而不管它们的顺序如何 ,即。 the predicate 谓词

(term1='A' && term2='B') OR (`term1='B' && term2='A')

holds true, then I just want to update column number. 是的,那我只是想更新列号。 Is there any way of doing that? 有没有办法做到这一点?

A (perhaps the ) clean way to handle this situation is to use INSERT ... ON DUPLICATE KEY UPDATE , read the documentation . 处理这种情况的一种(也许干净的方法是使用INSERT ... ON DUPLICATE KEY UPDATE阅读文档

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row 如果指定ON DUPLICATE KEY UPDATE,并且插入的行将导致UNIQUE索引或PRIMARY KEY中出现重复值,则MySQL将执行旧行的UPDATE

The important part is would cause a duplicate value in a UNIQUE index . 重要的部分是在UNIQUE索引中导致重复值 Therefore you need to create an multicolumn unique index . 因此,您需要创建多列唯一索引

Now I'm not sure if you can manage the order that way, therefore I'd create an extra field with the concatenation of the sorted values of your fields, and have that field uniquely indexed. 现在我不确定你是否可以通过这种方式管理订单,因此我会创建一个额外的字段,其中包含字段的排序值的串联,并且该字段具有唯一索引。

EDIT : Instead of storing the concatenation your fields, you could also just store the hash and index it. 编辑 :您可以只存储哈希并将其编入索引,而不是存储字段的串联。

Thanks @okiharaherbst, 谢谢@okiharaherbst,

This is what I did: I added new column "uniqueKey" as primary key and insert goes as follows: 这就是我所做的:我添加了新列“uniqueKey”作为主键,插入如下:

INSERT INTO table1(term1,term2,num,uniquekey) VALUES ( "a","b",10, 
concat(greatest(term1,term2),least(term1,term2))) on duplicate key update num=10;

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

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