MySQL current_insert_id()? (不是last_insert_id())
我正在插入一行,其中包含一个 char 列,用于基于(除其他外)行的自动 id 的哈希值。
我知道我可以插入它,获取 insert_id,计算哈希值,然后更新它。
有谁知道在单个查询中执行此操作的方法? 您在插入时需要行 insert_id 。 这是完全不可能的,还是有类似 current_insert_id() 的东西......
谢谢!
I am inserting a row with a char column for a hash based on (among other things) the row's auto id.
I know I can insert it, fetch the insert_id, calculate the hash, and update it.
Does anyone know of a way to do this in a single query? You would need the rows insert_id at the time of insert. Is that completely impossible, or is there something like current_insert_id()...
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,MySQL 中没有函数可以为您提供
current_insert_id()
。从 MySQL 中的
AUTO_INCRMENT
字段获取生成的 ID 值的唯一方法是执行 INSERT,然后调用last_insert_id()
。 因此,您可能需要执行单独的 UPDATE 来计算哈希值的计划。我可以想到另外两个替代方案:
在 INSERT 之前使用除
AUTO_INCRMENT
之外的其他机制自行生成唯一值。 例如,请参阅UUID()
函数。
不要在哈希计算中包含 ID。
No, there's no function in MySQL that gives you the
current_insert_id()
.The only way to get a generated ID value from an
AUTO_INCREMENT
field in MySQL is to do the INSERT and then calllast_insert_id()
. So your plan of doing a separate UPDATE to calculate the hash is probably what you'll have to do.I can think of two other alternatives:
Generate the unique value yourself before the INSERT with some other mechanism besides the
AUTO_INCREMENT
. For example, see theUUID()
function.Don't include the ID in your hash calculation.
据我所知,没有办法在 MySQL 中通过一个查询来完成此操作,但您可以在您选择的服务器端脚本语言中执行类似的操作:
...这为您提供了要合并到 SQL 中的 id。
编辑:我还找到了这个答案< /a> 这可能会有所帮助。
There's no way that I know of to do it in MySQL in one query, but you could do something like this in your server-side scripting language of choice:
...which gives you the id to incorporate in your SQL.
EDIT: I also found this answer which may be helpful.
您可以从
information_schema
.TABLES
表中查询下一个要使用的值,其中的AUTO_INCRMENT
列。 (你可能正在为自己设置竞争条件?)You can query the next-to-be-used value from the
information_schema
.TABLES
table, theAUTO_INCREMENT
column there. (You might be setting yourself up for a race condition?)当我进行插入时,我会执行如下操作:
INSERT INTO table (col1,col2) VALUES (data1,data2);SELECT LAST_INSERT_ID()
并像获取数据一样运行查询。 在 VB.NET 中,语法是(假设您有 MySql.Data.MySqlClient .dll):
从技术上讲,它是两个查询,但仅对数据库进行一次命中:)
When I do inserts I do something like this:
INSERT INTO table (col1,col2) VALUES (data1,data2);SELECT LAST_INSERT_ID()
and just run the query like I was fetching data. In VB.NET the syntax is (assuming you have the MySql.Data.MySqlClient .dll):
It's technically two queries, but only one hit on the database :)