在 MySQL 数据库中,我需要创建一个新的 closure
表(称为 closure_new
),将两列外键集成到另一个表,概念
。这意味着将不在 closure
中的行添加到 closure_new
。如何设置 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 以使用与每个 subtypeId
和每个 supertypeId 关联的每个
?effectiveTime
值的记录填充 closure_new
表
这是概念
表:
CREATE TABLE `concept` (
`id` BIGINT NOT NULL DEFAULT 0,
`effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
`some other fields`,
PRIMARY KEY (`id`,`effectiveTime`)
) ENGINE=InnoDB;
这是旧的闭包
表:
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;
最佳答案
试试这个:
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
你的数据更好匹配,否则你会有一些外键约束问题
关于mysql - 来自同一张表的两个复合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23748815/