[英]How to insert values into two tables with a foreign key relationship on mySql
[英]How to insert into values into two table with foreign key relationship built in?
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;
现在,当我想插入答案时:
我可以做类似的事情吗?
插入答案( content
)联接问题( title
, content
)VALUE(“ Ironman”,“喜欢的字符”,“谁是Avanger中您喜欢的字符?”);
还是有更好的方法来做类似的事情?
最好的方法是通过某种方式保留问题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?'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.