1

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???")   
3
  • You have to get the sector_id first somehow Sep 1, 2013 at 15:09
  • Just treat the foreign key value for what it is - an ordinary integer. It can be inserted just as any other value.
    – halfer
    Sep 1, 2013 at 15:10
  • Yeah, I was thinking about getting the sector ID in somehow. But I think I'll be doing a second read to get the Sector ID inside the 'Constituent' crud method... Sep 1, 2013 at 15:14

2 Answers 2

1

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

0

Assuming there is a sector with sector_name 'sector 1' you could do something like this.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.