Naarciss
Naarciss

Reputation: 21

MySQL INSERT INTO SELECT JOIN

I'm trying to modify old MySQL base to new - I hope better. So I've got a question because I can't handle it myself:

I've got an old table which has 5 columns:

*table_old*
id | name_1 | name_2 | name_3 | role 
 1 |    aaa |    bbb |    ccc |    g 
 2 |    aaa |    ccc |    ddd |    f 
 3 |    bbb |    aaa |    ddd |    g 

and so on.

I made a new table to store name values with 2 columns and it looks like that:

*table_name*
id | name 
 1 |  aaa
 2 |  bbb
 3 |  ccc
 4 |  ddd

Because I'm naming new tables using it role (last column from old table) I can create new table with 4 columns so:

*table_g*
id | name_1 | name_2 | name_3
 1 |    aaa |    bbb |    ccc
 2 |    bbb |    aaa |    ddd

*table_f*
id | name_1 | name_2 | name_3
 1 |    aaa |    ccc |    ddd

Also because the name can be very long I would prefer to use id value from table 2 instead name - I would like to get something like that:

*table_g*
id | id_1 | id_2 | id_3
 1 |    1 |    2 |    3
 2 |    2 |    1 |    4

*table_f*
id | id_1 | id_2 | id_3
1  |    1 |    3 |    4

I changed name of columns from *name_1* to *id_1* etc.

Now I'm asking for help. I'm trying to use something like that:

INSERT INTO `table_g`(`id_1`, `id_2`, `id_3`)
SELECT `table_name`.`id`,`table_name`.`id`,`table_name`.`id`
FROM `table_name` 
  RIGHT JOIN `table_old` ON `table_name`.`name` = `table_old`.`name_1`
  RIGHT JOIN `table_old` ON `table_name`.`name` = `table_old`.`name_2`
  RIGHT JOIN `table_old` ON `table_name`.`name` = `table_old`.`name_3`
WHERE `table_old`.`role` = 'g';

But this doesn't work... Please help if you can :/

Upvotes: 1

Views: 24544

Answers (1)

Attila Fulop
Attila Fulop

Reputation: 7011

INSERT INTO `table_g`(`id_1`, `id_2`, `id_3`)
SELECT t1.`id`, t2.`id`, t3.`id`
FROM `table_name` tn
  RIGHT JOIN `table_old` t1 ON tn.`name` = t1.`name_1` AND t1.`role` = 'g'
  RIGHT JOIN `table_old` t2 ON tn.`name` = t2.`name_2` AND t2.`role` = 'g'
  RIGHT JOIN `table_old` t3 ON tn.`name` = t3.`name_3` AND t3.`role` = 'g'

At first sight there's much ambiguity in your select, so at least you should try what happens using the code above.

Upvotes: 4

Related Questions