如何将值插入到内置外键关系的两个表中?

时间:2012-10-07 00:07:20

标签: mysql foreign-key-relationship

以下2个表结构(由sequel pro生成):

问题表:

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;

答案表:

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;

现在,当我想插入答案时:

我可以这样做:

INSERT INTO回答(content)加入问题(titlecontent)VALUE('铁人',“最喜欢的角色”,“谁是你最喜欢的Avanger角色?”) ;

还是有更好的方法来做类似的事情吗?

1 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是以某种方式保留问题ID并使用它来插入答案。 如果没有别的办法,你可以这样做:

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?'));