0

如下所示的 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 answer( content) JOIN question( title, content) VALUE('Ironman',"favourite characters","Avanger 中你最喜欢的角色是谁?");

或者有没有更好的方法来做类似的事情?

4

1 回答 1

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?'));
于 2012-10-07T00:36:18.000 回答