0

I have a table Product that has a manufacturer field. The manufacturer field is currently of type VARCHAR.

I thought it better to create a table Manufacturer and alter the Product table to include a manufacturer_id field which of course shall be a foreign key referencing Manufacturer.id

So to migrate the data I want to insert into the new Product.manufacturer_id field the id of the Manufacturer whose name corresponds to the current Product.manufacturer field.

I'm having problems migrating the data using the following query:

INSERT INTO Product (manufacturer_id) 
   SELECT m.id FROM Manufacturer AS m WHERE m.name =
   SELECT p.manufacturer FROM Product AS p WHERE p.manufacturer = m.name;

Can anyone point me to where I'm going wrong?

1

1 Answer 1

4

You want update, not insert:

update p
    set manufacturer_id = m.id
    from product p join
         manufacturer m
         on p.manufacturer = m.name;

The above is SQL Server syntax (not sure why I did that; the question is clearly tagged MySQL). The correct MySQL syntax is:

update product p join
       manufacturer m
       on p.manufacturer = m.name
    set p.manufacturer_id = m.id;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply and for getting me on the right track. I couldn't get the above query to work but the following sorted things: UPDATE Product p INNER JOIN Manufacturer m on p.manufacturer = m.name SET p.manufacturer_id = m.id;

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.