简体   繁体   English

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

[英]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 ): 2个表结构如下(由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?"); 插入答案( content )联接问题( titlecontent )VALUE(“ Ironman”,“喜欢的字符”,“谁是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. 最好的方法是通过某种方式保留问题ID并使用它插入答案。 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?'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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