我有三个桌子
LineItem Orders Product
order_id order_id product_id
product_id order_date product_name
quantity customer_id list_price
price employee_id
total
我要向行项目插入新值,其中价格的计算方式为:价格=数量* product.list_price如何使用INSERT INTO来做到这一点?
您可以使用insert ... select
语法。假设您要插入order_id
1
,product_id
2和quantity
3
:
insert into line_item(order_id, product_id, quantity, price)
select
1,
product_id,
3,
3 * list_price
from product
where product_id = 2
GMB的解决方案是完美的。如果要更新表中所有现有行的价格,也可以在此之上使用update。
UPDATE l
SET l.price = p.list_price * l.quantity
FROM LineItem l
JOIN Product p ON p.product_id = l.product_id