[英]MYSQL How to update child table value with foreign key while insert data based on parent table
I have 2 table, a parent table and child table. 我有2个表,一个父表和一个子表。 Child table has foreign key to parent table. 子表具有指向父表的外键。 I have successfully create the foreign key. 我已经成功创建了外键。 But how to auto update field 'nama' based on parent table while I only insert 'id_parent' ? 但是,当我仅插入“ id_parent”时,如何基于父表自动更新字段“ nama”? I only tried : 我只试过:
INSERT INTO child (id_parent) values (1)
but field 'name' value is still NULL 但是字段“名称”的值仍为NULL
Here my tables : 这是我的桌子:
CREATE TABLE `child` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`id_parent` int(6) DEFAULT NULL,
`nama` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `aa` (`nama`,`id_parent`),
CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=armscii8;
-- ----------------------------
-- Table structure for parent
-- ----------------------------
CREATE TABLE `parent` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`nama` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `nama` (`nama`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=armscii8;
the parent table has data like this 父表具有这样的数据
INSERT INTO `parent` VALUES ('4', 'asa');
INSERT INTO `parent` VALUES ('1', 'batman');
INSERT INTO `parent` VALUES ('3', 'goku');
INSERT INTO `parent` VALUES ('2', 'robin');
INSERT INTO `parent` VALUES ('5', 'usu');
Check this line: 检查这一行:
KEY `aa` (`nama`,`id_parent`),
CONSTRAINT `aa` FOREIGN KEY (`nama`, `id_parent`) REFERENCES `parent` (`nama`, `id`)
here you have created a foreign key
relationship on two column ie parent
( nama
, id
). 在这里,您已经在两列(即parent
( nama
, id
))上创建了foreign key
关系。 In that case you can only insert those combination values in child table that are already in parent table. 在这种情况下,您只能在父表中已经存在的子表中插入这些组合值。 Remember, here foreign key is implemented by combining two columns, not on a single column. 请记住,这里的外键是通过组合两列而不是在单个列上来实现的。
In my case I had a Location TransId column in my child table. 就我而言,我的子表中有一个Location TransId列。 I have update the location name from the parent ti child table column. 我已经从父ti子表列中更新了位置名称。 I done with the below 我做了以下
UPDATE Table_A SET Table_A.CityName = Table_B.LocationDesc 更新Table_A SET Table_A.CityName = Table_B.LocationDesc
from 从
<ParentTable> AS Table_A
INNER JOIN <ChildTable> AS Table_B
ON Table_A.CityTransID = Table_B.TransID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.