update if two fields exists, insert if not (MySQL)(如果两个字段存在则更新,如果不存在则插入(MySQL))
问题描述
这不是 这个问题 所以我开始了一个新的.
This isn't an (exact) duplicate of this questions so I'Ve started a new one.
我有这张表(ID 是主要的并且自动递增)
I have this table (ID is primary and auto increment)
ID | mykey | myfoo | mybar
============================
1 | 1.1 | abc | 123
2 | 1.1.1 | def | 456
3 | 1.2 | abc | 789
4 | 1.1 | ghi | 999
仅当 mykey = '1.1' AND myfoo = 'abc'
I would like to UPDATE row 1 with mybar = "333" only if mykey = '1.1' AND myfoo = 'abc'
如果 mykey != '1.1' OR myfoo != 'abc' 我想插入一个新行.
If either mykey != '1.1' OR myfoo != 'abc' I would like to INSERT an new row.
用一个语句就可以做到吗?
Is this possible with one statement?
推荐答案
MySQL 中的唯一索引不必位于单个列上.您只需在 ALTER TABLE..ADD UNIQUE 语句中指定更多列,即可在多个列上添加唯一索引:
A unique index in MySQL does not have to be on a single column. You can add a UNIQUE index on multiple columns simply by specifying more columns in your ALTER TABLE..ADD UNIQUE statement:
ALTER TABLE myTable ADD UNIQUE (
mykey,
myfoo
);
现在您可以使用常规的 INSERT INTO...ON DUPLICATE KEY 语句.
Now you can use a regular INSERT INTO...ON DUPLICATE KEY statement.
SQLFiddle 演示(注意没有添加多个重复值 - 所有其他值都是)
注意:
如果其中任何一个为 NULL,则它将不被视为唯一.mykey 是 'bar' 和 myfoo 是 NULL 可以添加到无穷大,即使它们具有相同"的值(NULL 并不是真正的值).
If either is NULL, it will not be counted as unique. mykey being 'bar' and myfoo being NULL could be added to infinity even though they have the "same" values (NULL isn't really a value).
这篇关于如果两个字段存在则更新,如果不存在则插入(MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果两个字段存在则更新,如果不存在则插入(MySQL)
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
