Question

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 ;

master

id, comments
 1, 'text 1' 

detail

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

and I want to duplicate them as follows with one or two queries:

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

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

I've managed to copy master only using temporary table, but the problem is with the detail. It is copied with master_id 1 not 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 *

duplicating rows with master.id = 1 when we already inserted row 2

2nd query fixed as follows:

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 )
Was it helpful?

Solution

You don't need a temporary table to copy the master, you can do:

INSERT INTO master (comments)
SELECT comments FROM master;

To copy the details, I think this should do it:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top