Reputation: 95
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?
Upvotes: 0
Views: 753
Reputation: 1271121
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;
Upvotes: 4