douyao4632 2018-06-05 11:10
浏览 96

INSERT IGNORE因auto_increment失败

My goal is to only execute a SQL Insert if the same value not exists.

this is my table1:

id(auto_increment)
version(string)

My Query looks like this:

INSERT IGNORE INTO table1 (version) VALUES ('12345');

The problem is that the ignore statement not work because every row is different because of the id column (auto_increment).

Anybody here have a Solution to avoid double saving the same values?

Solution:

INSERT INTO table1 (version)
SELECT * FROM (SELECT '12345') AS tmp
WHERE NOT EXISTS (
    SELECT version FROM table1 WHERE version = '12345'
) LIMIT 1;
  • 写回答

1条回答 默认 最新

  • dqcqcqwq38860 2018-06-05 11:11
    关注

    Your issue has nothing to do with the auto-incremented column.

    You need a unique constraint/index on version:

    alter table table1 constraint unq_table1_version unique (version);
    

    I also don't recommend insert ignore for this purpose. It might ignore other errors. Instead, use on duplicate key update:

    insert into table1 (version) 
        values ('12345')
        on duplicate key update version = values(version);  -- this is a no-op
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料