问题
i need to create a trigger that multiply two fields from two tables, but i have no idea of how to do it, so let's see if you can help me.
Two tables,
Products (product_name, price)
Orders (product_name (foreign key),units_ordered)
I need to add another field on table the Orders that multiply price from Products and units_ordered from Orders, so : total_price = price (from products) X units_ordered (from Orders)
Thanks in advance, and sorry for my bad english. Regards
回答1:
You don't need trigger at all. And also you don't need to add another column for the total price as it is already redundant.
If you want their total prices, just do it during the projection of records. Example
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
or you can create a VIEW
out of your SELECT
statement. Example,
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
and selecting from the view,
SELECT * FROM ProductOrder
But if you really want to add another column, still trigger is not an option. You only need to update the values for that column using UPDATE
and joining of the two tables. Assuming your new column is called TotalPrice
on table `Orders.
UPDATE Orders a
INNER JOIN Products b
ON a.Product_name = b.Product_name
SET a.TotalPrice = a.units_ordered * b.Price
来源:https://stackoverflow.com/questions/15989477/trigger-multiply-from-two-tables