21

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();
voutasaurus
  • 2,968
  • 2
  • 24
  • 37
Kaah
  • 915
  • 3
  • 11
  • 26

2 Answers2

33

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()
Kaah
  • 915
  • 3
  • 11
  • 26
  • 1
    I have a similar case in which the primary key of my table is varchar(36) which contains a uuid values generated by trigger with the each new insertion . I am updating an already existing code so the primary key was auto increament int value which used with LastInsertedRow , now i need to edit this so i added an additional column id_tracker which is an autoincreament column but not a primary key . is it possible to use it ? – Laila Jan 05 '21 at 12:14
1

Try following:

UPDATE items
SET qwe = 'qwe',
    item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();
Wolfack
  • 2,667
  • 1
  • 26
  • 50