如何进行多次插入并获取id

发布于 2024-09-02 14:22:10 字数 260 浏览 3 评论 0原文

将一些数据插入表中

(id PK autoincrement, val)

我想使用 multi insert

INSERT INTO tab (val) VALUES (1), (2), (3) 

是否可以获得最后插入的 id 的表?

我这样问是因为我不确定是否全部都采用这种形式:(n,n+1,n+2)。

我使用mysql inodb。

I want to insert some data into a table

(id PK autoincrement, val)

with use multi insert

INSERT INTO tab (val) VALUES (1), (2), (3) 

Is it possible to obtain a table of last inserted ids?

I'm asking becouse I'm not sure if all will in this form: (n, n+1, n+2).

I use mysql inodb.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街角卖回忆 2024-09-09 14:22:10

来自 mysql 文档

如果您使用
单个 INSERT 语句,
LAST_INSERT_ID() 返回值
为第一个插入行生成
仅有的。这样做的原因是为了
可以轻松地重现
针对某些相同的 INSERT 语句
其他服务器。

From the mysql docs:

If you insert multiple rows using a
single INSERT statement,
LAST_INSERT_ID() returns the value
generated for the first inserted row
only. The reason for this is to make
it possible to reproduce easily the
same INSERT statement against some
other server.

病毒体 2024-09-09 14:22:10

这里有人在 mysql 论坛上问同样的问题,但没有给出真正权威的答案。他们降落在“为了安全起见,先锁上桌子”。然后你就可以算出连续的 id。

我的建议是:

如果您要插入许多行并且不介意阻塞其他线程,请锁定表,执行插入,然后解锁。由于表被锁定,您可以指望插入的 id 是连续的(或者无论您的自动增量设置是什么)。

如果您正在进行少量插入或不想阻塞其他线程,只需一次执行一个插入,然后在每次插入后调用 last_insert_id() 。

Here's someone asking the same question on the mysql forums, but no really authoritative answer is given. They land on 'To be safe, lock the table first. Then you can count in the ids being sequential.'

My advice is this:

If you're inserting many rows and don't mind blocking other threads, lock the table, do the inserts, and then unlock. Since the table was locked, you can count on the inserted ids being sequential (or whatever your autoincrement setting is).

If you're doing a small number of inserts or don't want to block other threads, just do them one at a time and call last_insert_id() after each.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文