How do I get the id of the last updated row in MySQL and Go?

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

I am using go-sql driver. It should work with these two requests, 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();

+3


source to share


2 answers


Working solution. It is so simple. I hope someone else finds 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()

      

+4


source


Try the following:



UPDATE items
SET qwe = 'qwe',
    item_id=LAST_INSERT_ID(item_id)
WHERE asd = 'asd';
SELECT LAST_INSERT_ID();

      

0


source







All Articles