我需要创建一个触发器,将两个表中的两个字段相乘,但我不知道如何操作,所以让我们看看你是否可以帮助我。
两张桌子,
产品(product_name,价格)
订单(product_name(外键),units_ordered)
我需要在表格上添加另一个字段,其中产品的价格乘以产品和单位订单的订单,因此:total_price = price(来自产品)X units_ordered(来自订单)
提前致谢,抱歉我的英语不好。 此致
答案 0 :(得分:0)
根本不需要触发器。而且您也不需要为总价格添加另一列,因为它已经是多余的。
如果您想要他们的总价格,只需在记录投影期间进行。实施例
SELECT a.Product_Name,
a.Price,
b.units_ordered,
a.Price * b.units_ordered AS TotalPrice
FROM Products a
INNER JOIN Orders b
ON a.Product_name = b.Product_name
或者您可以在VIEW
声明中创建SELECT
。例如,
CREATE VIEW ProductOrder
AS
SELECT a.Product_Name,
a.Price,
b.units_ordered,
a.Price * b.units_ordered AS TotalPrice
FROM Products a
INNER JOIN Orders b
ON a.Product_name = b.Product_name
并从视图中选择,
SELECT * FROM ProductOrder
但是如果你真的想要添加另一个列,仍然不能选择触发器。您只需使用UPDATE
更新该列的值并连接两个表。假设您的新列在表'Orders。'上被称为TotalPrice
。
UPDATE Orders a
INNER JOIN Products b
ON a.Product_name = b.Product_name
SET a.TotalPrice = a.units_ordered * b.Price