2017-05-11 34 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;