且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-21 02:56:41

使用REPLACE-与INSERT完全相同,不同之处在于,如果表中的旧行与PRIMARY KEY的新行具有相同的值,或者唯一索引,在插入新行之前删除旧行.

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;