特定表格中最后插入的ID [英] Last inserted id from specific table

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

问题描述

SELECT LAST_INSERT_ID() as id FROM table1

为什么该查询有时返回除table1以外的另一个表的最后插入的ID? 我在Node.js(db-mysql插件)中调用它,我只能执行查询.

Why does this query sometimes return the last inserted id of another table other than table1? I call it in Node.js (db-mysql plugin) and I can only do queries.

推荐答案

LAST_INSERT_ID()只能告诉您针对整个数据库连接的最新自动生成的ID ID ,而不是针对每个单独的表,这也是为什么查询只应读取SELECT LAST_INSERT_ID()而不指定表的原因. 一旦在该连接上触发另一个INSERT查询,它就会被覆盖.如果要在插入到某个表时生成ID,则必须在执行此操作后立即运行SELECT LAST_INSERT_ID()(或使用某些可以执行此操作的API函数).

LAST_INSERT_ID() can only tell you the ID of the most recently auto-generated ID for that entire database connection, not for each individual table, which is also why the query should only read SELECT LAST_INSERT_ID() - without specifying a table.
As soon as you fire off another INSERT query on that connection, it gets overwritten. If you want the generated ID when you insert to some table, you must run SELECT LAST_INSERT_ID() immediately after doing that (or use some API function which does this for you).

如果要在任意表中当前最新的ID,则必须在该表上执行SELECT MAX(id),其中idID列的名称.但是,如果该行已被删除,则不一定是最近生成的ID;如果另一个连接设法在您自己的INSERTINSERT之间执行了INSERT,则它不一定是由您的连接生成的.您选择的ID.

If you want the newest ID currently in an arbitrary table, you have to do a SELECT MAX(id) on that table, where id is the name of your ID column. However, this is not necessarily the most recently generated ID, in case that row has been deleted, nor is it necessarily one generated from your connection, in case another connection manages to perform an INSERT between your own INSERT and your selection of the ID.

(作为记录,您的查询实际上返回N行,其中包含该数据库连接上最近生成的ID,其中N是table1中的行数.)

(For the record, your query actually returns N rows containing the most recently generated ID on that database connection, where N is the number of rows in table1.)

这篇关于特定表格中最后插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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