Note that there are some explanatory texts on larger screens.

plurals
  1. POMYSQL: How do I create a trigger that calculates a field value based on value from different table?
    primarykey
    data
    text
    <p>In <em>table A</em> I have fields <code>CENA</code>(price), <code>cena_za_kus</code>(price_per_piece), <code>mnozstvi</code>(quantity).<br> In <em>table B</em> I have field <code>DPH</code>(vat).</p> <p>I'd like to add a before update/insert trigger, which would calculate the value of <code>PRICE</code> field, something like this: </p> <pre><code>price = (price_per_piece * count) + (price_per_piece * count * tableB.vat) </code></pre> <p>Is this possible? Thank you.</p> <p>Edit: And the row in <em>table</em> A has a foreign_key <code>dph_id</code> pointing to the corresponding row in <em>table B</em>.</p> <pre><code> 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; </code></pre> <p>and </p> <pre><code>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 ; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload