在表A 中,我有字段CENA
(价格),cena_za_kus
(price_per_piece),mnozstvi
(数量)。
在表B 中,我有字段DPH
(增值税)。
我想添加一个更新前/插入触发器,它会计算PRICE
字段的值,如下所示:
price = (price_per_piece * count) + (price_per_piece * count * tableB.vat)
这可能吗? 谢谢。
编辑:表 A中的行有一个foreign_key dph_id
指向表B 中的相应行。
CREATE TABLE `polozky` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`objednavka_id` int(11) NOT NULL,
`dph_id` int(11) NOT NULL,
`polozka` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`cena` float NOT NULL,
`mnozstvi` int(11) NOT NULL,
`cena_za_kus` float NOT NULL,
PRIMARY KEY (`id`),
KEY `IdObjednavka` (`objednavka_id`,`dph_id`),
KEY `objednavka_id` (`objednavka_id`),
KEY `dph_id` (`dph_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=63663 ;
ALTER TABLE `polozky`
ADD CONSTRAINT `polozky_ibfk_7` FOREIGN KEY (`objednavka_id`) REFERENCES `objednavky` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `polozky_ibfk_8` FOREIGN KEY (`dph_id`) REFERENCES `dph` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
和
CREATE TABLE `dph` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sekce` varchar(64) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'nastaveni',
`popis` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
`DPH` int(11) unsigned NOT NULL,
`poradi` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `DPH_2` (`DPH`),
UNIQUE KEY `popis` (`popis`),
KEY `DPH` (`DPH`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=9 ;
答案 0 :(得分:3)
试试这个:
DELIMITER $$
CREATE TRIGGER `yourDB_polozky`
BEFORE INSERT
ON `yourDB`.`polozky`
FOR EACH ROW
BEGIN
DECLARE vat_rate float;
SELECT DPH
INTO dph_rate
FROM `yourDB`.`dph`
WHERE id = new.dph_id;
SET new.cena = (1 + dph_rate) * (new.cena_za_kus * new.mnozstvi);
END
$$