I have a table called FOODS
. FOODS
has two foreign keys: IDsize
and IDflavor
.
The parent tables FLAVOR
and SIZE
each have a column price
.
The table FLAVOR
has columns IDflavor
, flavor
and price
with an example row (1, 'Beef', 10). The table SIZE
has columns IDsize
, size
and price
with an example row (3, 'BIG', 15).
Is it possible to make a column in FOODS
that will automatically sum the values of the price
columns of the corresponding rows in the parent tables FLAVOR
and SIZE
(using the foreign keys)? So if FOODS
has IDsize = 3
and IDflavor = 1
, the column should automatically get 25 (10+15).
Best Answer
What you're asking to do is a type of denormalisation: You're adding redundant data to a single table in order to avoid having to query multiple tables to get the same information. This is done to increase performance of
SELECT
queries and/or simplify such queries.Since the
price
columns are in different tables / rows, you unfortunately can't use generated columns.So you're going to have to consider other options:
You could use a
VIEW
on top of theFOODS
table which summed theprice
s from the two parent tables. So whenever you wanted toSELECT
from theFOODS
table (and you wanted to includesum_price
), you insteadSELECT
ed from thisVIEW
. Something like:CREATE VIEW V_FOODS([the columns of FOODS], sum_price) AS SELECT [the columns of FOODS], FLAVOR.price + SIZE.price AS "sum_price" FROM FOODS INNER JOIN FLAVOR USING(IDflavor) INNER JOIN SIZE USING (IDsize);
(As pointed out by RDFozz, note that this isn't actually denormalisation of the data, since the actual data stay in the parent tables.)
You could use
TRIGGER
s to populate asum_price
column inFOODS
. You would need a trigger onUPDATE
s to each ofFLAVOR
andSIZE
, and a trigger onINSERT
s toFOODS
.You could have a
sum_price
column inFOODS
and give your application the responsibility of keeping it up-to-date.You could also give up and not denormalise. Just let your application join
FOODS
,FLAVOR
andSIZE
whenever you need the sum of prices.