MySQL ON DUPLICATE KEY-最后插入ID? [英] MySQL ON DUPLICATE KEY - last insert id?

查看:92
本文介绍了MySQL ON DUPLICATE KEY-最后插入ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

INSERT INTO table (a) VALUES (0)
  ON DUPLICATE KEY UPDATE a=1

我想要插入或更新的ID.通常我会运行第二个查询来获取此信息,因为我相信insert_id()仅返回插入的" ID,而不返回更新的ID.

I want the ID of either the insert or the update. Usually I run a second query in order to get this as I believe insert_id() only returns the 'inserted' ID and not the updated ID.

是否可以在不运行两个查询的情况下进行INSERT/UPDATE和检索行ID?

Is there a way to INSERT/UPDATE and retrieve the ID of the row without running two queries?

推荐答案

签出此页面:

Check this page out: https://web.archive.org/web/20150329004325/https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
At the bottom of the page they explain how you can make LAST_INSERT_ID meaningful for updates by passing an expression to that MySQL function.

来自MySQL文档示例:

From the MySQL documentation example:

如果表包含AUTO_INCREMENT列,并且INSERT ... UPDATE插入一行,则LAST_INSERT_ID()函数将返回AUTO_INCREMENT值.如果该语句改为更新一行,则LAST_INSERT_ID()没有意义.但是,您可以通过使用LAST_INSERT_ID(expr)解决此问题.假设id是AUTO_INCREMENT列.要使LAST_INSERT_ID()对于更新有意义,请按如下所示插入行:

If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). 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;

这篇关于MySQL ON DUPLICATE KEY-最后插入ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆