[英]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.