MySQL SELECT LAST_INSERT_ID() 作为复合键。 是否可以?

发布于 2024-07-10 14:51:26 字数 44 浏览 22 评论 0原文

我可以获得 MySQL 中复合键的 LAST INSERT ID() 吗?

Can I get the LAST INSERT ID() for a compound key in MySQL?

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

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

发布评论

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

评论(1

乙白 2024-07-17 14:51:26

是的。 一个表中不能有多个自增字段。

CREATE TABLE foo (
  id1 int(11) NOT NULL auto_increment,
  id2 int(11) NOT NULL default '0',
  PRIMARY KEY  (id1, id2)
);

INSERT INTO foo VALUES (DEFAULT, 2);

SELECT LAST_INSERT_ID(); -- returns 1, the value generated for id1

LAST_INSERT_ID() 仅返回声明为 AUTO_INCRMENT 的列的值。 没有函数可以返回不是由系统生成的复合主键中的值。 您应该已经知道该值,因为您刚刚在 INSERT 语句中给出了它。 棘手的情况是当触发器或某些东西覆盖该值时。

Yes. You can't have multiple auto-increment fields in a single table.

CREATE TABLE foo (
  id1 int(11) NOT NULL auto_increment,
  id2 int(11) NOT NULL default '0',
  PRIMARY KEY  (id1, id2)
);

INSERT INTO foo VALUES (DEFAULT, 2);

SELECT LAST_INSERT_ID(); -- returns 1, the value generated for id1

LAST_INSERT_ID() returns the value only for a column declared AUTO_INCREMENT. There's no function to return the value in a compound primary key that wasn't generated by the system. You ought to know that value already, since you just gave it in an INSERT statement. The tricky case would be when a trigger or something overrides the value.

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