Insert values referring to another table

 ̄綄美尐妖づ 提交于 2020-01-15 10:19:26

问题


I have created the following simple datamodel:

I used the following insert statements to insert values:

1) Table Products:

INSERT INTO test.products
(ProductName, Price)
VALUES 
("Product A","99,99"),
("Product B","49,95"), 
("Product C","5,95");

2) Table Orders:

INSERT INTO test.orders
(Customer)
VALUES 
("Customer A"),
("Customer B"), 
("Customer B");

All this works fine so far.


However, now I also want to insert values into the table Products_per_Order.
As you can see in the datamodel the Products_per_Order table contains the column Price. In this column I want to insert the price referring to the ID in the column Products_idProducts. Therefore, I tried to go with the following insert statement but could not make it work so far:

INSERT INTO test.products_per_order
(Orders_idOrders, Products_idProducts, Price, Quantity)
VALUES
("1","1",(Select Price from test.products),"5"),
("1","2",(Select Price from test.products),"4"),
("2","1",(Select Price from test.products),"10"),
("3","2",(Select Price from test.products),"3"),
("3","3",(Select Price from test.products),"9");

Do you have any idea how to solve this issue?


回答1:


I would recommend using insert . . . select instead:

insert into test.products_per_order (Orders_idOrders, Products_idProducts, Price, Quantity)
    select x.idOrder, x.idProduct, p.price, x.qty
    from (select 1 as idOrder, 2 as idProduct, 5 as qty union all
          select 1 as idOrder, 2 as idProduct, 4 as qty union all
          . . .  -- I've left these out so you can see the structure of the query
          select 3 as idOrder, 3 as idProduct, 9 as qty
         ) x left join
         test.products p
         on p.idProducts = x.idProduct;

This makes it much less likely that a typo will result in the wrong price.




回答2:


You can use sub-query to extract it from the Products table.

("2","1","Select Price from test.products where test.products.idProducts = '1')","10");



回答3:


You are close, but you when you have (Select Price from test.products) this selects all prices from the test.products table. You need to make it so it returns one value.

INSERT INTO test.products_per_order
(Orders_idOrders, Products_idProducts, Price, Quantity)
VALUES
("1","1",(Select Price from test.products WHERE test.products.idProducts = '1'),"5"),
("1","2",(Select Price from test.products WHERE test.products.idProducts = '2'),"4"),
("2","1",(Select Price from test.products WHERE test.products.idProducts = '1'),"10"),
("3","2",(Select Price from test.products WHERE test.products.idProducts = '2'),"3"),
("3","3",(Select Price from test.products WHERE test.products.idProducts = '3'),"9");


来源:https://stackoverflow.com/questions/54311635/insert-values-referring-to-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!