Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在内置外键关系的两个表中插入值?_Mysql_Foreign Key Relationship - Fatal编程技术网

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

Mysql 如何在内置外键关系的两个表中插入值?,mysql,foreign-key-relationship,Mysql,Foreign Key Relationship,两个表结构如下(由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 T

两个表结构如下(由
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;
现在,当我想插入答案时:

我可以做一些类似于:

在答案(
内容
)中插入连接问题(
标题
内容
)值('Ironman','Favorite characters','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?'));

我想这就是你想要的:谢谢,伙计,select语句可以做这类事情,这是惊人的,顺便说一句,你能为这种高级sql命令提供一些资源吗?请检查我最后一个与这个问题相关的问题,但是使用CodeIgniter activerecord ORM来存档同样的事情