Answer the question
In order to leave comments, you need to log in
Triggers in MySQL
This is a continuation of the database design story.
The beginning is here: habrahabr.ru/qa/6019/
I decided to use triggers to calculate the balance of a certain product.
The goal is this: after adding information about the sale or receipt of goods to the `variation` table, the balance of goods at a certain outlet should be recalculated. The `balance` table (for example, after adding a new outlet) may not have records that can be updated . Therefore, you need to add them there.
Wrote the following trigger:
BEGIN
SET @item_id := NEW.item_id;
SET @place_id := NEW.`place_id`;
SET @item_count := NEW.`count`;
IF (`balance`.`item_id` AND `balance`.place_id) = NULL THEN
INSERT INTO `balance` (`item_id`,`place_id`,`count`) VALUES (@item_id,@place_id,@item_count);
END IF;
IF (`balance`.`item_id` AND `balance`.place_id) IS NOT NULL THEN
UPDATE `balance` SET
`balance`.`count`=`count` + @item_count
WHERE `place_id` = @place_id AND `item_id` = @item_id;
END IF;
END
Answer the question
In order to leave comments, you need to log in
I think it swears at checks
IF (`balance`.`item_id` AND `balance`.place_id) = NULL THEN
Try to use INSERT ... ON DUPLICATE KEY UPDATE, then IF is not needed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question