在MySQL数据库中,我需要创建一个新的closure
表(称为closure_new
),它将两列外键集成到另一个表concept
。这意味着将行添加到不在closure_new
中的closure
。如何设置SQL来完成此任务?
这是我第一次尝试填充closure_new
:
INSERT INTO `closure_new`
SELECT o.subtypeId, d.id, d.effectiveTime
FROM concept d
JOIN closure o
ON o.subtypeId = d.id;
请注意,我的第一次尝试仅针对subtypeId/subtype_effectiveTime
,可能无法完全解决。 SQL还需要合并supertypeId/supertype_effectiveTime
。如何编写SQL以填充closure_new
表,其中包含与每个effectiveTime
和每个subtypeId
相关联的每个supertypeId
值的记录?
这是concept
表:
CREATE TABLE `concept` (
`id` BIGINT NOT NULL DEFAULT 0,
`effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
`some other fields`,
PRIMARY KEY (`id`,`effectiveTime`)
) ENGINE=InnoDB;
这是旧closure
表:
CREATE TABLE `closure` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`subtypeId` BIGINT(20) NOT NULL ,
`supertypeId` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`)
);
这是closure_new
表,需要填充我上面开始编写的脚本:
CREATE TABLE `closure_new` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`subtypeId` BIGINT(20) NOT NULL ,
`subtype_effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
`supertypeId` BIGINT(20) NOT NULL ,
`supertype_effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
FOREIGN KEY (`supertypeId`, `supertype_effectiveTime`) references concept(`id`, `effectiveTime`),
FOREIGN KEY (`subtypeId`, `subtype_effectiveTime`) references concept(`id`, `effectiveTime`)
); ENGINE=InnoDB;
答案 0 :(得分:2)
试试这个:
insert into closure_new
(subtypeId, subtype_effectiveTime, supertypeId, supertype_effectiveTime)
select cl.id, co.effectiveTime, co.id, co.effectiveTime from closure cl inner join concept co
您的数据更匹配,或者您将遇到一些外键约束问题
答案 1 :(得分:1)
不确定我是否完全理解你所追求的是什么,但是如何:
INSERT INTO `closure_new` (subtypeId, subtype_effectiveTime, supertypeId, supertype_effectiveTime)
SELECT subCon.id, subCon.effectiveTime, superCon.id, superCOn.effectiveTimed.effectiveTime
FROM closure o, concept subCon, concept superCon
where subcon.Id = o.subtypeId and supercon.Id = o.supertypeId
或者可能,您可以使用该选择语句create view
。