我有主 - 细节表,我想复制它们

时间:2014-04-19 18:16:10

标签: mysql copy duplicates master-detail

CREATE TABLE IF NOT EXISTS `master` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `comments` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `detail` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `master_id` int(10) unsigned NOT NULL,
  `value` int(10) DEFAULT 0,
  PRIMARY KEY (`id`)
) AUTO_INCREMENT=1 ;

id, comments
 1, 'text 1' 

细节

id, master_id, value
 1, 1,          50 
 2, 1,          53

我希望通过一两个查询将它们复制如下:

id, comments 
 1, 'text 1' 
 2, 'text 1' *

id, master_id, value
 1, 1,          50 
 2, 1,          53 
 3, 2,          50 *
 4, 2,          53 *

我设法只使用临时表复制master,但问题在于详细信息。它与master_id 1而不是2

一起复制
id, comments 
 1, 'text 1' 
 2, 'text 2'
 3, 'text 1' *

id, master_id, value
 1, 1,          50 
 2, 1,          53 
 3, 2,          51 
 4, 2,          66 
 5, 2,          44 
 6, 3,          50 *
 7, 3,          53 *

当我们已插入第2行

时,使用master.id = 1复制行

第二个查询修正如下:

INSERT INTO detail ( master_id, value )
SELECT m2.id, value
FROM detail AS d
JOIN master AS m1 ON m1.id = d.master_id AND m1.id = @DUPLICATETHISID
JOIN master AS m2 ON m2.comments = m1.comments AND m2.id != m1.id 
AND m2.id not IN ( SELECT master_id FROM detail JOIN master as m ON master_id = m.id )

1 个答案:

答案 0 :(得分:0)

您不需要临时表来复制主文件,您可以这样做:

INSERT INTO master (comments)
SELECT comments FROM master;

要复制详细信息,我认为应该这样做:

INSERT INTO detail (master_id, value)
SELECT m2.id, value
FROM detail AS d
JOIN master AS m1 ON m1.id = d.master_id
JOIN master AS m2 ON m2.comments = m1.comments AND m2.id != m1.id

DEMO