1

我有两个表,A 和 B。在表 B 中插入新行时,如何插入 FK 作为对表 A 中记录的引用?

我有以下两个表格:

--
-- Table structure for table `sector`
--

CREATE TABLE IF NOT EXISTS `sector` (
  `sector_id` int(11) NOT NULL AUTO_INCREMENT,
  `sector_name` varchar(100) NOT NULL,
  `sector_url` varchar(500) NOT NULL,
  PRIMARY KEY (`sector_id`),
  UNIQUE KEY `sector_id` (`sector_id`,`sector_name`,`sector_url`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `constituent` (
  `constituent_id` int(11) NOT NULL AUTO_INCREMENT,
  `constituent_name` varchar(100) DEFAULT '',
  `constituent_ticker` varchar(10) NOT NULL,
  `constituent_isin_number` varchar(50) DEFAULT '',
  `constituent_currency` varchar(10) DEFAULT '',
  `sector_id` int(11) NOT NULL,
  PRIMARY KEY (`constituent_id`),
  KEY `sector_id` (`sector_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


--
-- Constraints for table `constituent`
--
ALTER TABLE `constituent`
  ADD CONSTRAINT `constituent_ibfk_1` FOREIGN KEY (`sector_id`) REFERENCES `sector` (`sector_id`);

当我进行插入时,如何构造查询,以便当我插入表“组成”时,我使用“扇区”的主键?

INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sectorFK) 
values ("the name", "the ticker", "the number", "the currency", "the foreign key???")   
4

2 回答 2

1

为了能够在插入 table 后获得主键值B,为了将其插入 table A,您可以使用last_insert_id()函数,当不使用参数时返回为AUTO_INCREMENT列设置的最后一个自动生成的值:

例如:

insert into B(col)
  values(1);

insert into A(t1_id, col)
  values(last_insert_id(), 2);

insert into A(t1_id, col)
  values(last_insert_id(), 3);

SQLFiddle 演示

于 2013-09-01T15:22:17.450 回答
0

假设有一个扇区名称为“扇区 1”,你可以做这样的事情。

INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sector_id) (select 'the name', 'the ticker', 'the number', 'the currency', sector_id from sector where sector_name = "sector 1");
于 2013-09-01T15:20:34.013 回答