gpt4 book ai didi

java - 如何连续插入外键?

转载 作者:行者123 更新时间:2023-11-29 00:26:45 24 4
gpt4 key购买 nike

我有两个表,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`);

当我执行插入操作时,如何构建查询以便当我插入表“constituent”时,我使用的是“sector”的主键?

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???")

最佳答案

为了能够在插入表 B 后获得主键值,以便将其插入表 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 Demo

关于java - 如何连续插入外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com