SQL field as sum of other fields

2019-06-24 03:42发布

This is not query related, what I would like to know is if it's possible to have a field in a column being displayed as a sum of other fields. A bit like Excel does.

As an example, I have two tables:

Recipes

nrecepie integer
name varchar(255)
time integer

and the other

Instructions

nintrucion integer
nrecepie integer
time integer

So, basically as a recipe has n instructions I would like that

recipes.time = sum(intructions.time)

Is this possible to be done in create table script?? if so, how?

标签: sql field sum
5条回答
We Are One
2楼-- · 2019-06-24 04:08

You can use a view:

CREATE VIEW recipes_with_time AS
SELECT nrecepie, name, SUM(Instructions.time) AS total_time
FROM Recepies
JOIN Instructions USING (nrecepie)
GROUP BY Recepies.nrecepie

If you really want to have that data in the real table, you must use a trigger.

查看更多
放荡不羁爱自由
3楼-- · 2019-06-24 04:08

This could be done with an INSERT/UPDATE/DELETE trigger. Every time data is changed in table Instructions, the trigger would run and update the time value in Recepies.

查看更多
我想做一个坏孩纸
4楼-- · 2019-06-24 04:19

In general, you want to avoid situations like that because you're storing derived information (there are exceptions for performance reasons). Therefore, the best solution is to create a view as suggested by AndreKR. This provides an always-correct total that is as easy to SELECT from the database as if it were in an actual, stored column.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-06-24 04:26

Depends pn the database vendor... In SQL Server for example, you can create a column that calculates it's value based on the values of other columns in the same row. they are called calculated columns, and you do it like this:

Create Table MyTable
 (
     colA Integer,
     colB Integer,
     colC Intgeer,
     SumABC As colA + colB + colC
 )

In general just put the column name you want, the word 'as' and the formula or equation to ghenerate the value. This approach uses no aditonal storage, it calculates thevalue each time someone executes a select aganist it, so the table profile remains narrower, and you get better performance. The only downsode is you cannot put an index on a calculated column. (although there is a flag in SQL server that allows you to specify to the database that it should persist the value whenever it is created or updated... In which case it can be indexed)

In your example, however, you are accessing data from multiple rows in another table. To do this, you need a trigger as suggested by other respondants.

查看更多
叼着烟拽天下
6楼-- · 2019-06-24 04:28

You can use a trigger to update the time column everytime the instructions table is changed, but a more "normal" (less redundant) way would be to compute the time column via a group by clause on a join between the instructions and recepies [sic] table.

查看更多
登录 后发表回答