-1

I need to normalize my table. So I made a script (sql) which I execute. I would like to INSERT all existing Clients from table A (old) into table B (new).

It is simply done with

INSERT INTO `A` SELECT * FROM `B`;

but I want to set some foreign key values. There is a city field in table A but a city_idfield in table B. I thought of something like this:

INSERT INTO `A` (`id`, `name`, `city_id`)
SELECT `id`, `name` FROM `B`,
(SELECT `cities`.`id` FROM `cities` WHERE `cities`.`name` = (SELECT `city` FROM `A` WHERE `A`.`id` = `B`.`id`)) `temp_cities`;

Unfortunately this doesn't work, because B.id isn't set :-( The error is the following:

Error (1054): Unknown column 'B.id' in 'where clause')

At which point did I mess something up?

2
  • 1
    Please show the schemas of the tables.
    – Barmar
    Apr 22, 2013 at 23:01
  • Simplified (because the other stuff doesn't matter): A { id, name, city } B { id, name, city_id } cities { id, name }
    – lenny.myr
    Apr 22, 2013 at 23:14

1 Answer 1

0

just use syntax SELECT id AS 'city_id' FROM B , you can 'name' each column in your select and then you can insert it without any issues.

You can deactivate foreign keys constraint like this :

SET foreign_key_checks = 0;

and switch it back to

SET foreign_key_checks = 1;

after you finish query. It`s not best practice but sometimes it can help.

1
  • I don't know, if you understand what my problem is: I need to replace B.id (in the 2nd derived SELECT query) with the id of the current's INSERT row.
    – lenny.myr
    Apr 22, 2013 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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