Calculate column value from another column in anot

2020-06-06 04:56发布

问题:

I have a table that contains the unit price and other details of each item in a store.

CREATE TABLE Item (Item_id CHAR(4), Description CHAR(40), Sizes CHAR(40), Weight REAL, Unit_price REAL, PRIMARY KEY(Item_id));

And another one that contains details of the items contained in each order.

CREATE TABLE Order_contains_items (Item_id CHAR(4), Order_no INT, Quantity_ordered INT, Ordered_price REAL, PRIMARY KEY(Item_id, Order_no), FOREIGN KEY(Order_no) REFERENCES Order(Order_no), FOREIGN KEY(Item_id) REFERENCES Item(Item_id));

Now I want to compute

Order_contains_items.Ordered_price = Item.Unit_price * Order_contains_items.Quantity_ordered WHERE Order_contains_items.Item_id = Item.Item_id

Note that I want it to be a part of the table itself and not as a different view or a query. How can I do this? I looked into triggers and other mechanisms for this but do they work for values in different tables especially with such constraints?

I tried the following trigger based on Column calculated from another column? :

CREATE TRIGGER Order_price BEFORE INSERT ON Order_contains_items
    FOR EACH ROW BEGIN
        SET NEW.Ordered_price = Item.Unit_price * NEW.Quantity_ordered
            WHERE NEW.Item_id = Item.Item_i
END;

But it didn't seem to work

回答1:

Here is how you can do that in MySQL (your question is tagged with both mysql and sql-server)

CREATE TRIGGER tg_bi_order_contains_items 
BEFORE INSERT ON Order_contains_items
FOR EACH ROW
  SET NEW.Ordered_price = 
  (
    SELECT Unit_price * NEW.Quantity_ordered
      FROM Item
     WHERE Item_id = NEW.Item_id
     LIMIT 1
  );

CREATE TRIGGER tg_bu_order_contains_items 
BEFORE UPDATE ON Order_contains_items
FOR EACH ROW
  SET NEW.Ordered_price = 
  (
    SELECT Unit_price * NEW.Quantity_ordered
      FROM Item
     WHERE Item_id = NEW.Item_id
     LIMIT 1
  );

Here is SQLFiddle demo