mysql 条件插入 - 如果不存在插入

mysql conditional insert - if not exists insert(mysql 条件插入 - 如果不存在插入)
本文介绍了mysql 条件插入 - 如果不存在插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个查询只检查记录,如果它不存在插入?我不想重复更新或替换.寻找一个查询解决方案,查看其他答案,但不是我所希望的.

Is there a query that will just check for the record and if it doesn't exists insert? I don't want to on duplicate update or replace. Looking for a one query solution, looked at other answer but not really what I was hoping for.

表:

name|value|id
------------------
phill|person|12345

伪查询:

IF NOT EXISTS(name='phill', value='person', id=12345) INSERT INTO table_name

推荐答案

使用 REPLACE - 工作方式与 INSERT 完全相同,只是如果表中的旧行与新行具有相同的值PRIMARY KEY 或 UNIQUE 索引,在插入新行之前删除旧行.

Use REPLACE - works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

http://dev.mysql.com/doc/refman/5.0/en/replace.html

-- For your example query
REPLACE INTO table_name(name, value, id) VALUES
('phill', 'person', 12345) 

由于您不能使用 REPLACE 另一个选项是:为表数据设置约束索引(主键、唯一性)并使用 INSERT IGNORE

Since you can't use REPLACE another option is to: set constraint indexes for the table data (primary key, uniqueness) and use INSERT IGNORE

INSERT IGNORE INTO table_name
SET name = 'phill',
    value = 'person',
    id = 12345;

这篇关于mysql 条件插入 - 如果不存在插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)