1

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 :/

3
  • What exactly do you mean by "doesn't work"? Do you get an error? Is it something about 'ambiguous name', by any chance?
    – Mark Byers
    Commented Apr 19, 2012 at 12:00
  • Hum, I'm not sure, but I think you forgot some parenthesis: INSERT INTO table ()... (SELECT... FROM... JOINS WHERE...)
    – sp00m
    Commented Apr 19, 2012 at 12:02
  • no i got #1054 - Unknown column 'table_old'.'role' in 'where clause'
    – Naarciss
    Commented Apr 19, 2012 at 12:14

1 Answer 1

4
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.

3
  • Doesnt work :/ #1054 - Unknown column 't1.id' in 'field list'
    – Naarciss
    Commented Apr 19, 2012 at 13:00
  • what is the result of select * from table_old limit 1? Commented Apr 19, 2012 at 13:09
  • id | name_1 | name_2 | name_3 | role 1 | aaa | bbb | ccc | g i think ill just use UPDATE :/
    – Naarciss
    Commented Apr 19, 2012 at 14:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.