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)
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
