2012-07-20 63 views
3

我想從兩個不同的模式合併具有相同結構的兩個表。現在我通過下面的查詢這樣做:合併來自不同模式的兩個表以及更新的外鍵

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

當我合併來自不同模式2個tagitem表,然後合併sourcetagitem表的外鍵即tagitem應該更新tagitem ID合併後更新。

感謝,

+0

後的2代表的定義。 – 2012-07-20 14:32:03

+0

@ypercube我已編輯我的問題.. plz檢查它... – pbhle 2012-07-21 05:03:25

+0

你能否更新其中一個表中的所有ID,以便它們不會與第二個表中的ID發生衝突。您應該可以通過提供的單個UPDATE語句來執行此操作,並且在更新時將外鍵設置爲CASCADE。然後,當您將兩個表合併到一個表中時,仍保留原始ID。 – theon 2012-07-22 15:14:55

回答

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; 
相關問題