Insert Into Select Get ID From another Table

时间:2018-01-23 19:23:45

标签: sql

I have a DB that we built a few years ago that we're placing into an RDB. I want the following:

PlantName  PlantNumber  Customer  ProductNumber  Product
________________________________________________________
________________________________________________________
Loc A      1000         Joe's     123456         Pizza 1
________________________________________________________
Loc B      2000         Jerry's   654321         Pizza 2

Which is one table, to go into a new database with Plants, Customers and Products Tables. I have the Customers table already worked out:

CustomerID    CustomerName
____________________________
____________________________
987           Joe's
____________________________
789           Jerry's

And I want the Products Table to look as such

ProductID    CustomerID    ProductName    
_______________________________________
_______________________________________
123456       987           Pizza 1
_______________________________________
654321       789           Pizza 2

So my question is, how can I create an INSERT Statement to get the CustomerID from the Customers Table? I would need to select both from the old Products Table and the new Customers Table to ge the ProductID and the CustomerID values.

2 个答案:

答案 0 :(得分:0)

You can use regular INSERT syntax using a nested SELECT statement. See this link for example: Insert into ... values ( SELECT ... FROM ... )

INSERT INTO Products ( ProductID, CustomerID, ProductName )
SELECT  12345, CustomerID, 'Product name'
FROM    Customers
WHERE   CustomerName = 'name'  

But as the comment suggests, you'd probably want to create a third mapping table that handles this data for you. One table strictly for customers, one for products, and a third one for purchases/customer product mapping.

You might also be interested in normal forms for databases: https://en.wikipedia.org/wiki/First_normal_form which can help you design your tables in a cleaner, easier to maintain fashion.

答案 1 :(得分:0)

You can use SELECT INTO statement.

SELECT A.ProductNumber as ProductID, B.CustomerID, A.Product as ProductName 
INTO Products
FROM Plants as A
INNER JOIN Customers as B
ON B.CustomerName = A.Customer

The drawback is if CustomerName is not unique and refers to a different person. So the good design is your original table has CustomerId instead CustomerName.