插入引用另一个表的值

时间:2019-01-22 15:35:51

标签: mysql sql mysql-workbench

我创建了以下简单的datamodel

enter image description here

我使用以下insert statements插入值:

1)表产品

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

2)表订单

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

到目前为止,所有这些都工作正常。


但是,现在我也想在表Products_per_Order中插入值。
如您在datamodel中所见,Products_per_Order表包含列Price。在此列中,我要插入指向Products_idProducts列中的 ID 的价格。因此,我尝试使用以下insert statement,但到目前为止无法正常工作:

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");

您知道如何解决此问题吗?

3 个答案:

答案 0 :(得分:1)

您可以使用子查询将其从“产品”表中提取出来。

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

答案 1 :(得分:1)

您已经接近,但是当您拥有(Select Price from test.products)时,您将从test.products表中选择所有价格。您需要使其返回一个值。

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");

答案 2 :(得分:0)

我建议改用insert . . . select

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;

这使错字导致错误价格的可能性大大降低。