dongshi1148
2017-05-22 22:52
浏览 383

如何获取MySQL和Go中最后插入的行的ID?

How can I use this trick: How to get ID of the last updated row in MySQL? in Go (golang)?

I am using the go-sql-driver. It should work with these two queries but how can I do it in Go?

INSERT INTO table (unique_id) VALUES ("test")
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);

SELECT LAST_INSERT_ID();
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxuan0698 2017-05-22 23:08
    已采纳

    Working solution. It is as simple as that. I hope someone else will find this useful:

    stmt, err := db.Prepare("INSERT table SET unique_id=? ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)")
    
    res, err := stmt.Exec(unique_id)
    
    lid, err := res.LastInsertId()
    
    点赞 打赏 评论
  • dongyuan7110 2017-11-23 11:56

    Try following:

    UPDATE items
    SET qwe = 'qwe',
        item_id=LAST_INSERT_ID(item_id)
    WHERE asd = 'asd';
    SELECT LAST_INSERT_ID();
    
    点赞 打赏 评论

相关推荐 更多相似问题