MySQL SELECT LAST_INSERT_ID() for compound key. Is it possible?

↘锁芯ラ 提交于 2019-12-02 00:21:37

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/372388/mysql-select-last-insert-id-for-compound-key-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!