简体   繁体   中英

MySQL insert into table selecting data from another table

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM