简体   繁体   中英

How to insert a foreign key in a row?

I have two tables, A and B. When inserting a new row into table B, how do I insert a FK as a reference to a record in table A?

I've got the two below tables:

--
-- 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`);

When I do an insert, how can I structure the query such that when I insert into the table 'constituent', I'm using the primary key of '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???")   

To be able to get a primary key value after inserting into table B , in order to insert it into the table A , you could use last_insert_id() function, which when used without a parameter returns a last automatically generated value that was set for an AUTO_INCREMENT column:

For example:

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

假设有一个扇区的扇区名称为“ sector 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM