【问题标题】:merge two tables from different schemas along with updated foreign keys合并来自不同模式的两个表以及更新的外键
【发布时间】:2026-01-24 10:05:01
【问题描述】:

我想合并来自两个不同模式的具有相同结构的两个表。现在我正在通过以下查询执行此操作:

    INSERT INTO schema1.table1(col1,col2)
    SELECT col1,col2
    FROM schema2.table1;

此查询将两个表很好地合并为一个,但未更新外键。它们与原始表格中的相同。那么有没有什么办法呢。

    CREATE TABLE  `research_delta`.`source` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `url` varchar(500) COLLATE utf8_bin NOT NULL,
  `createdOn` datetime NOT NULL,
  `modifiedOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `isDeleted` tinyint(4) NOT NULL DEFAULT '0',
  `structure` mediumblob,
  `firstRunStatus` varchar(50) COLLATE utf8_bin NOT NULL DEFAULT '0',
  `isMaster` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='All the sources supported by the system';



CREATE TABLE  `research_delta`.`sourcetagitem` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `source` bigint(20) DEFAULT NULL,
  `tagItem` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_source_sourcetagitem` (`source`),
  KEY `fk_tagItem_sourcetagitem` (`tagItem`),
  CONSTRAINT `fk_source_sourcetagitem` FOREIGN KEY (`source`) REFERENCES `source` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `fk_tagItem_sourcetagitem` FOREIGN KEY (`tagItem`) REFERENCES `tagitem` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=287 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


CREATE TABLE  `research_delta`.`tagitem` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8_bin NOT NULL,
  `description` varchar(1000) COLLATE utf8_bin DEFAULT NULL COMMENT 'this field will contain any description details about the type of category or tag..',
  `parentId` bigint(20) DEFAULT NULL COMMENT 'if the category or tag in subject to be under any other catefory or tag then this field will contain the id of the category that it is under.',
  `createdOn` datetime DEFAULT NULL,
  `modifiedOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isDeleted` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=286 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='this table represents the tags and categories supported by a';

当我合并来自不同模式的两个 tagitem 表然后合并 sourcetagitem 表时,外键即 tagitem 应该在合并后使用更新的 tagitem id 进行更新。

谢谢,

【问题讨论】:

  • 贴出两张表的定义。
  • @ypercube 我已经编辑了我的问题.. 请检查一下...
  • 您能否更新其中一张表中的所有 ID,以免它们与第二张表中的 ID 冲突。如果在更新时将外键设置为 CASCADE,您应该能够使用单个 UPDATE 语句来执行此操作。那么当你把两张表合并成一张表的时候,仍然保持原来的ID。

标签: mysql foreign-key-relationship


【解决方案1】:

是否真的需要合并它们,或者当你想查询数据时可以使用联合吗?

(SELECT * FROM schema1.table1) UNION (SELECT * FROM schema2.table1)

或者以同样的方式创建视图...

CREATE VIEW view1 AS  (SELECT * FROM schema1.table1) UNION (SELECT * FROM schema2.table1);

然后从中选择您感兴趣的任何内容

SELECT col1 FROM vv;

【讨论】: