3

表 A 中,我有字段CENA(价格)、cena_za_kus(价格每件)、mnozstvi(数量)。
表 B 中,我有字段DPH(增值税)。

我想添加一个更新/插入之前的触发器,它将计算PRICE字段的值,如下所示:

price = (price_per_piece * count) + (price_per_piece * count * tableB.vat)

这可能吗?谢谢你。

编辑:A 中的行有一个 foreign_keydph_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 ;
4

1 回答 1

4

尝试这个:

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
$$
于 2013-03-25T15:26:25.193 回答