2017-05-11 30 views
0

我正在开发一个小型开票解决方案,我需要添加一列来存储一个单位的价格。我已经为所有单位和数据库中的数量添加了一列。在更新Postgresql数据库时进行数学计算

我的问题是,我如何添加此列并使用精确的数字填充它?我知道,公式为:

total_col/quantity_col = unit_col

+0

不要创建一个列。在查询时计算。 –

回答

1

假设您的数据库称为mydb,该表称为invoices,且列unit_col我会做到以下几点:

连接到你的PostgreSQL数据库通过命令行,通常psql mydb然后执行下列操作:

ALTER TABLE invoices 
ADD COLUMN unit_col real; 

UPDATE invoices SET unit_col = total_col/quantity_col; 
2

这里是填充与SOM的新列的一个例子e衍生值:

create table products (
    total_col int, 
    quantity_col int); 

ALTER TABLE products ADD COLUMN unit_col numeric(10,2) default null; 
update products set unit_col=total_col::float/quantity_col; 

您需要设置触发器以保持此列处于最新状态。这就是所谓的持久计算列。

另一个,也许是更好的,解决办法是建立有你想要的计算列一个观点:

create table products (
    total_col int, 
    quantity_col int); 

create view productsWithUnitCol as 
    select *, total_col::float/quantity_col as unit_col from products;