Update another table after insert using a trigger?

后端 未结 1 1448
广开言路
广开言路 2021-01-15 05:47

I\'m currently creating some sort of inventory system.

I have tbl1 where in I save the items. In tbl1, I have column qty or th

相关标签:
1条回答
  • 2021-01-15 06:11

    If you're not expecting huge amounts of data use a view or a stored procedure to calculate on the fly and return actual quantity. It may save you a lot of headache in the long run.

    Your view (actually views) might look like

    CREATE VIEW vw_table2_sum AS
    SELECT product, SUM(issued_qty) qty
      FROM Table2
     GROUP BY product;
    
    CREATE VIEW vw_table1 AS
    SELECT t.id, t.product, t.qty - COALESCE(v.qty, 0) qty
      FROM Table1 t LEFT JOIN vw_table2_sum v
        ON t.product = v.product;
    

    When we do

    SELECT * FROM vw_table1;
    

    will get

    | ID |  PRODUCT | QTY |
    -----------------------
    |  1 |    mouse |   8 | -- the quantity is current
    |  2 | keyboard |  15 |
    |  3 |  monitor |   8 |
    

    Here is SQLFiddle demo

    Now if you for some reason want to manage your inventory quantity with a trigger it might look like this

    CREATE TRIGGER tg_ai_table2
    AFTER INSERT ON table2
    FOR EACH ROW
      UPDATE Table1
         SET qty = qty - NEW.issued_qty
       WHERE product = NEW.product;
    

    Here is SQLFiddle demo

    0 讨论(0)
提交回复
热议问题