合并来自不同模式的两个表以及更新的外键

时间:2012-07-20 11:34:09

标签: mysql foreign-key-relationship

我想从两个不同的模式合并两个具有相同结构的表。现在我通过以下查询来做到这一点:

    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更新。

谢谢,

1 个答案:

答案 0 :(得分:0)

实际上是否需要合并它们,或者在想要查询数据时是否可以使用联合?

(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;