如何获取一个表的自动增量ID并插入另一个表中

时间:2014-05-26 04:48:55

标签: mysql sql

我有一个mysql表,其描述如下:

Create Table

CREATE TABLE `question` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `category` varchar(255) DEFAULT NULL,
  `is_deleted` bit(1) NOT NULL,
  `question` varchar(255) DEFAULT NULL,
  `version` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8

我有另一张桌子

Create Table

CREATE TABLE `parent_question` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `is_deleted` bit(1) NOT NULL,
  `version` int(11) DEFAULT NULL,
  `pid` bigint(20) NOT NULL,
  `qid` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK8FEA83DBE860AF9` (`pid`),
  KEY `FK8FEA83DBF34C20F6` (`qid`),
  CONSTRAINT `FK8FEA83DBE860AF9` FOREIGN KEY (`pid`) REFERENCES `parent` (`id`),
  CONSTRAINT `FK8FEA83DBF34C20F6` FOREIGN KEY (`qid`) REFERENCES `question` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8

我有权在问题表中插入一行。所以当我添加新行时,将生成id(因为它是auto_increment)并且我想将此id存储在{{1 field qid table。

有人可以告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

使用last_insert_id()功能:

insert into question values (...);
insert into parent_question values (..., last_insert_id(), ...);
相关问题