【问题标题】:MySQL insert ignore: is it possible to tell which insert failed?MySQL插入忽略:是否可以判断哪个插入失败?
【发布时间】:2021-01-10 03:16:19
【问题描述】:

例如如果我有:

insert ignore into users (email)
values ('exists@example.com'), ('doesnt-exist@example.com')

如果email 是唯一的并且已经有一行带有exists@example.com,则只插入1 行。是否可以判断插入了 2 行中的哪一行?

据我所知,insertId 指的是插入的第一行,但我不知道是哪一行。

【问题讨论】:

    标签: mysql sql sql-insert create-table


    【解决方案1】:

    这回答了相反的问题,即没有插入了哪些值。我不确定这是否有兴趣。

    但如果是这样,您可以将这个技巧与on duplicate key update 一起使用:

    insert into users (email)
        values ('exists@example.com'), ('doesnt-exist@example.com')
        on duplicate key update email = (case when @emails := concat_ws(',', @emails, values(email)) then values(email) else values(email) end);
        
    select @emails;
    

    这是一个 dbfiddle。

    【讨论】:

      【解决方案2】:

      在 MySQL 中,一种选择是在表中添加另一列,以跟踪更新每一行的最后日期:

      create table users (
          id int auto_increment primary key, 
          email varchar(50) unique,
          updated_at timestamp default current_timestamp on update current_timestamp  
      );
      

      现在,说表格的内容是:

      编号 |电子邮件 |更新时间 -: | :----------------- | :----------------- 1 |存在@example.com | 2020-09-23 00:00:00

      您运行插入语句,该语句尝试插入一个重复项:

      insert ignore into users (email)
      values ('exists@example.com'), ('doesnt-exist@example.com')
      

      您可以使用updated_at 来识别插入了哪一行:

      编号 |电子邮件 |更新时间 -: | :------------------------ | :----------------- 1 |存在@example.com | 2020-09-23 00:00:00 2 |不存在@example.com | 2020-09-23 22:33:42

      Demo on DB Fiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多