插入带有计算列的语句

时间:2019-01-23 07:05:35

标签: 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中,我想通过将OrderValuePrice相乘来计算最后一列Quantity。 因此,我尝试使用以下两个选项来回答答案here,但仍无法使它们起作用:

注意::列Price从表idProduct中获取基于Products的价格。
此功能已起作用。只有与数量的乘法不起作用。

选项1:

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

选项2:

INSERT INTO test.products_per_order 
(Orders_idOrders, Products_idProducts, Price, Quantity, OrderValue)
    SELECT m.idOrder, m.idProduct, p.price, m.qty, p.price * m.qty
    FROM (SELECT 1 as idOrder, 1 as idProduct, 5 as qty UNION ALL
          SELECT 1 as idOrder, 2 as idProduct, 4 as qty UNION ALL
          SELECT 2 as idOrder, 1 as idProduct, 10 as qty UNION ALL
          SELECT 3 as idOrder, 2 as idProduct, 3 as qty UNION ALL
          SELECT 3 as idOrder, 3 as idProduct, 9 as qty
         ) m
    LEFT JOIN test.products p on p.idProducts = m.idProduct;

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

2 个答案:

答案 0 :(得分:1)

您写道OrderValue是一个计算列,为什么不让数据库为您计算呢?

使用alter tableOrderValue列更改为生成的列,如下所示:

alter table test.products_per_order 
modify column OrderValue int generated always as (Price * Quantity) stored;

这样,您根本不需要插入它-您的插入将变成这样:

INSERT INTO test.products_per_order 
(Orders_idOrders, Products_idProducts, Price, Quantity)
    SELECT m.idOrder, m.idProduct, p.price, m.qty
    FROM (SELECT 1 as idOrder, 1 as idProduct, 5 as qty UNION ALL
          SELECT 1 as idOrder, 2 as idProduct, 4 as qty UNION ALL
          SELECT 2 as idOrder, 1 as idProduct, 10 as qty UNION ALL
          SELECT 3 as idOrder, 2 as idProduct, 3 as qty UNION ALL
          SELECT 3 as idOrder, 3 as idProduct, 9 as qty
         ) m
    LEFT JOIN test.products p on p.idProducts = m.idProduct;

答案 1 :(得分:0)

关于以下问题的评论,问题是表prices中的Products需要使用.作为小数分隔符而不是,来存储

如果将表INSERT STATEMENT的{​​{1}}修改为:

Products

,然后在选项2 中运行代码,一切正常。

INSERT INTO test.products
(ProductName, Price)
VALUES 
("Product A","99.99"),
("Product B","49.95"), 
("Product C","5.95");