S
S
Stepan2011-03-23 14:14:45
MySQL
Stepan, 2011-03-23 14:14:45

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

When adding a row to the `variation` table, the following message pops up: Unknown table 'balance' in field list.
With what it can be connected, I do not understand.
And is it possible to somehow more elegantly (and more correctly) check for the presence of corresponding rows in the `balance` table?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
camokatik, 2011-03-23
@steff

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.

G
gkirok, 2011-03-23
@gkirok

and the equal sign on IS should not be changed? Or is this an idea?

IF (`balance`.`item_id` AND `balance`.place_id) = NULL THEN

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question