Answer the question
In order to leave comments, you need to log in
Checks in MySQL triggers
There was a need to check a certain value before adding/updating it in the database.
There is the following table:
CREATE TABLE `balance` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`item_id` INT(10) NOT NULL DEFAULT '0',
`place_id` INT(10) NOT NULL DEFAULT '0',
`count` INT(10) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE INDEX `i_pl_itm` (`item_id`, `place_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
BEGIN
SET @item_id := NEW.`item_id`;
SET @place_id := NEW.`place_id`;
SET @item_count := NEW.`count`;
INSERT INTO `balance` (`item_id`,`place_id`,`count`)
VALUES (@item_id,@place_id,@item_count)
ON DUPLICATE KEY UPDATE `count`=`count` + @item_count;
END
CREATE TABLE `variation` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`person_id` INT(11) NOT NULL DEFAULT '0',
`place_id` INT(11) NOT NULL DEFAULT '0',
`item_id` INT(10) NOT NULL DEFAULT '0',
`date` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
`item_count` INT(11) NOT NULL DEFAULT '0',
`summ` DOUBLE(10,2) UNSIGNED NOT NULL DEFAULT '0.00',
PRIMARY KEY (`id`),
INDEX `i_date` (`date`),
INDEX `i_item` (`item_id`),
INDEX `i_place` (`place_id`),
INDEX `i_person` (`person_id`),
INDEX `i_dt_pl` (`date`, `place_id`),
INDEX `i_dt_pn` (`date`, `person_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
Answer the question
In order to leave comments, you need to log in
Dig towards transactions, stored procedures and select for update.
And no triggers.
Slightly updated the question.
The trigger wrote:
BEGIN
SET @real_count := (SELECT `count` FROM `balance` WHERE
`item_id` = NEW.`item_id` AND
`place_id` = NEW.`place_id`);
IF (@real_count >= NEW.`item_count`) THEN
SET @item_id := NEW.`item_id`;
SET @place_id := NEW.`place_id`;
SET @item_count := NEW.`item_count`;
INSERT INTO `balance` (`item_id`,`place_id`,`count`)
VALUES (@item_id,@place_id,@item_count)
ON DUPLICATE KEY UPDATE `count`=`count` + @item_count;
END IF;
END
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question