MySQL如何在使用INSERT IGNORE INTO时检索LAST_INSERT_ID的ID?

时间:2012-03-30 12:52:35

标签: mysql insert

Scenerio:

  1. 我将CSV文件插入我的数据库。
  2. 我使用jdbc驱动程序迭代文件并执行我的插入
  3. nameunique,因此当相同值到达时,插入不会更改表格
  4. 我使用INSERT INTO IGNORE来防止迭代在事件发生时中断
  5. 我使用LAST_INSERT_ID()在插入的下一个表中添加为FK
  6. INSERT_IGNORE发生时我得到0
  7. 如何解决此问题?

     Connection con = null;
    
        try
        {
          Class.forName("com.mysql.jdbc.Driver");
          con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
          con.setAutoCommit(false);
    
          Statement s1 = (Statement) con.createStatement();
          s1.executeUpdate("INSERT IGNORE INTO ORIGIN (ORI_NAME) VALUES(\""
              + d.getOriginName() + "\")");
    
          Statement s2 = (Statement) con.createStatement();
          s2.executeUpdate("INSERT IGNORE INTO STOCK (ORI_ID,S_TITLE) VALUES ("
              + "(SELECT ORI_ID FROM ORIGIN WHERE ORI_ID =LAST_INSERT_ID()),\""
              + d.getStockTitle() + "\")");
    
         }
    
          con.commit();
    
        }
        catch (Exception e)
        {
          if (con != null)
            try
            {
              con.rollback();
            }
            catch (SQLException e1)
            {
              e1.printStackTrace();
            }
    
          e.printStackTrace();
        }
        finally
        {
          if (con != null)
            try
            {
              con.close();
            }
            catch (SQLException e)
            {
              e.printStackTrace();
            }
        }
    

    要插入数据库的CSV文件示例

    US, P1, M, 200, 344
    US, P1, L, 233, 344
    US, P2, M, 444, 556
    MX, Q4, L, 656, 777
    

    表:http://sqlfiddle.com/#!2/b5752

2 个答案:

答案 0 :(得分:5)

您熟悉MySQL的ON DUPLICATE KEY UPDATE语法吗?

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

 // Results are the same as doing an update.
 // Note the way the PK can be used to avoid an IGNORE.
 s1.executeUpdate("INSERT INTO ORIGIN (ORI_NAME) VALUES(\""
          + d.getOriginName() + "\" ON DUPLICATE KEY UPDATE ORI_ID=ORI_ID)");

此处涉及维护网站的失败电子邮件地址的实际示例:

http://blog.developpez.com/james-poulson/p10016/sql/ne-rien-modifier-en-cas-de-duplicate-key/

至于检索最后插入的id,以下内容来自上面的mysql.com链接:

Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;

答案 1 :(得分:2)

如果要获取后续插入的ID,则代码必须测试LAST_INSERT_ID的0值,如果得到它,请在表上执行SELECT以找到插入的FK的正确值。

在伪代码中,这看起来像:

$err = mysql("insert ignore into mytable values ($x, $y)")
if($err){
    do something for an error
}
$id = mysql("select last_insert_id()");
if($id == 0){
    $id = mysql("select id from othertable where condition is true for the record I want to reference in my insert");
    if($id == 0){
        do something for error
    }
}
mysql("insert into othertable VALUES ($id, other stuff)")

您必须将其翻译成您自己的应用程序和语言。