简体   繁体   中英

How to insert into values into two table with foreign key relationship built in?

The 2 table structures like the following(generated by sequel pro ):

The question table:

CREATE TABLE `question` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL DEFAULT '',
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The answer table:

CREATE TABLE `answer` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `question_id` int(11) unsigned NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `question_id` (`question_id`),
  CONSTRAINT `answer_ibfk_1` FOREIGN KEY (`question_id`) REFERENCES `question` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now when I want to insert an answer:

Can I do something like:

INSERT INTO answer( content ) JOIN question( title , content ) VALUE('Ironman',"favourite characters","Who is your favourite characters in Avanger?");

or Is there a better way to do the similar thing?

The best way to do this is by in some way persisting the question id and using it to insert the answers. If there is no other way, you could do something like this:

INSERT INTO answer(content, question_id) 
VALUES('Ironman', (select id 
                     from question 
                    where title ='favourite characters' 
                      and content = 'Who is your favourite characters in Avanger?'));

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