gpt4 book ai didi

mysql - 插入带有计算列的语句

转载 作者:行者123 更新时间:2023-11-29 09:53:33 26 4
gpt4 key购买 nike

我创建了以下简单的 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 中我想计算最后一列OrderValue乘以PriceQuantity 。因此,我尝试使用以下两个选项来引用答案 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;

您知道如何解决这个问题吗?

最佳答案

您写道 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;

关于mysql - 插入带有计算列的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54321700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com