有一张表没有规范化。我希望对它进行规范化,并在创建引用时将数据分离到多个表中,所有这些都是通过存储过程完成的。
未规范化的表格:
Murder
(CaseID
,GunManufacturer
,GunName
,Villian
)
一些示例数据:
(40465893, 'BIG COMPANY','AK47', 'Dank Hank')
(34534566, 'SMALL COMPANY','Bazooka', 'King Kong')
现在,这里是我想要创建的表,并将这些信息分别推入。 请注意,这些表(带约束)已经创建,只需要添加数据。
`Event`
(
`VillianId`, `GunId`, `date`,
PRIMARY KEY (`VillianId`)
FOREIGN KEY (`VillianId`) REFERENCES `Villian` (`VillianId`)
FOREIGN KEY (`GunId`) REFERENCES `Gun` (`GunId`)
) ;
`Gun`
(
`GunId`,`ManufacturerId`,`GunName`,
PRIMARY KEY (`GunId`),
FOREIGN KEY (`ManufacturerId`) REFERENCES `Manufacturer` (`ManufacturerId`)
) ;
`Manufacturer`
(
`ManufacturerId`, `ManufacturerName`,
PRIMARY KEY (`ManufacturerId`)
) ;
`Villian`
(
`VillianId`, `VillianName`,
PRIMARY KEY (`VillianId`)
) ;
请忽略问题中的语法。只是想让它易于阅读。必须自动生成Id,因为单个表中当前不存在。我以前从未做过这种存储过程,只是寻找一些指导。不期待完整的解决方案。感谢。
答案 0 :(得分:0)
以下是一个可以满足您需求的示例:
DELIMITER ;;
CREATE PROCEDURE `UnpackMurder`()
BEGIN
INSERT INTO Manufacturer (ManufacturerName)
SELECT DISTINCT GunManufacturer
FROM Murder;
INSERT INTO Gun (ManufacturerId, GunName)
SELECT DISTINCT mf.ManufacturerId, md.GunName
FROM Murder md
JOIN Manufacturer mf ON md.GunManufacturer = mf.ManufacturerName;
INSERT INTO Villian (VillianName)
SELECT DISTINCT Villian
FROM Murder;
INSERT INTO `Event` (VillianId, GunId, `date`)
SELECT v.VillianId, g.GunId, md.`date`
FROM Murder md
JOIN Manufacturer mf ON md.GunManufacturer = mf.ManufacturerName
JOIN Gun g ON mf.ManufacturerId = g.ManufacturerId AND md.GunName = g.GunName
JOIN Villian v ON md.Villian = v.VillianName;
END;;
DELIMITER ;