我有一个包含3个表的数据库:
Orders(OrderId, OrderDate, OrderValue)
OrderDetails(DetailsId, OrderId, ProductId, Quantity)
Products(ProductId, ProductName, Price)
我需要在Orders中插入另一行。
我知道OrderId
,Date
,但我想计算OrderValue
。
我不知道该怎么做:OrderValue就是这样的。
(quantity*price)
其中OrderDetails.ProductId=Products.ProductId
OrderDetails
中OrderDetails.OrderId=Orders.OrderId
答案 0 :(得分:1)
最好的方法是使用View计算OrderValue,因为每次更改Quantity
或Price
时都应更新此字段。这是不好的,它与3NF相矛盾,你也会有很多其他的问题。我强烈建议您更改数据库结构,但如果您不想更改,可以使用以下示例:
insert into Orders(OrderId, OrderDate, OrderValue)
values(@SomeOrderID,getdate(), 0)
insert into Products(ProductId, ProductName, Price)
values(/*some values*/)
insert into OrderDetails(DetailsId, OrderId, ProductId, Quantity)
values(/*some values, include @SomeOrderID*/)
update o set OrderValue = (p.Price* pd.Quantity)
from Orders o
inner join OrderDetails pd on pd.OrderId = o.OrderId
inner join Products p on p.ProductId = pd.ProductId
where o.OrderId= @SomeOrderID
答案 1 :(得分:0)
如果这是Oracle,那么你可以尝试这个
INSERT INTO orders
(orderid,
orderdate,
ordervalue)
SELECT A.orderid,
A.orderdate,
A.quantity * B.price
FROM orderdetails A
inner join products B
ON A.productid = c.productid;