mysql - 来自同一张表的两个复合键

标签 mysql sql

在 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/

相关文章:

sql - Postgres 函数比查询/Postgres 8.4 慢

mysql - 不同的值作为另一列中的字符串

php - 如何调试 PDO 数据库查询?

即使有索引,mysql 文件排序也会发生 -- 我该如何修复

mysql - 哪个更高效 : Multiple MySQL tables or one large table?

sql - 如何在 sql 查询中使用两个连接?句法

mysql - 加载第一列固定宽度的 SQL infile

mysql - SQL - 如何进行条件插入

java - 使用 Play Framework 2.3.8 使用 ebean ORM 和 java 制作注释树

mysql - SQL:如何使用唯一值更新列