我有两个表,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`);
当我执行插入操作时,如何构造查询,以便在插入表'component'时,我使用'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???")
答案 0 :(得分:1)
为了能够在插入表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);
答案 1 :(得分: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");