【问题标题】:MYSQL: How to avoid inserting duplicate records?MYSQL:如何避免插入重复记录?
【发布时间】:2018-06-29 04:39:26
【问题描述】:

我正在做如下插入语句:

Insert into table2 (host, ip, domain, statusnew) 
select hostname, ip, domain, "True" from table1 t1, table2 t2 
where t1.status = "Done"
and t2.statusnew not regexp "True"
limit 10
;

我添加了声明t2.statusnew not regexp "True" 只是为了确保没有重复插入。但是,它正在添加重复的行。

如何确保没有重复条目?

【问题讨论】:

  • 我认为这可能是 table1 t1, table2 t2 重复条目的原因。

标签: mysql join left-join inner-join crud


【解决方案1】:
INSERT INTO TABLE_2
  (id, name)
SELECT t1.id,
       t1.name
  FROM TABLE_1 t1
 WHERE NOT EXISTS(SELECT id FROM TABLE_2 t2 WHERE t2.id = t1.id)

【讨论】:

  • 我没有插入任何 id 值。 PK 是自动创建的。你能帮我在上面的查询中使用Not Exists吗?
【解决方案2】:

您好,您可以使用 IGNORE 关键字来避免重复记录。 喜欢:

  • INSERT IGNORE INTO employee (last_name, first_name) VALUES('Rinku', 'Gohel');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    相关资源
    最近更新 更多