2

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 the available stock left.

tbl1:

id product  qty
1  mouse    10
2  keyboard 15
3  monitor  8

I also have the table tbl2 where in I save all the transaction in issuing items. In this table there is issued_qty.

tbl2

id requested_by product  issued_qty
1  john         mouse    2

My problem is how can I INSERT a row into tbl2 at the same time UPDATE the tbl1.qty (tbl1.qty - tbl2.issued_qty).

for example: when I insert record in tbl2 in requested_by, product and qty_issued, I want the tbl1 to be automatically updated. since we issue 2 (qty) of mouse to John. the record of mouse in tbl1, should be automatically less to the no. of issued quantity in tbl2

My idea is to use TRIGGER

but unfortunately I have no success.. can you please help me with this one..

thanks.

peterm
  • 91,357
  • 15
  • 148
  • 157
ChocoMartin
  • 111
  • 1
  • 3
  • 12

1 Answers1

8

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

peterm
  • 91,357
  • 15
  • 148
  • 157