2012-05-07 44 views
3

我想創建一個帶有時間戳列的表。問題是,我希望月份和年份的組合是獨一無二的。我試過這個,但它沒有幫助:從獨特支票上的時間戳中提取月份和年份?

CREATE TABLE adempiere.SOIP_Deudas (
    --Columnas del sistema 
    SOIP_Deudas_ID  numeric(10)  NOT NULL PRIMARY KEY, 
    ad_client_id numeric(10)  NOT NULL, 
    ad_org_id numeric(10)  NOT NULL, 
    updatedby numeric(10)  NOT NULL, 
    createdby numeric(10)  NOT NULL, 
    updated  timestamp  NOT NULL, 
    created  timestamp  NOT NULL, 
    isactive char(1)  DEFAULT 'Y'::bpchar NOT NULL, 

    --Columnas del usuario 
    SOIP_Departamentos_ID numeric(10) NOT NULL, 
    fecha  timestamp NOT NULL, 
    monto  real  NOT NULL DEFAULT 0, 

    FOREIGN KEY (SOIP_Departamatos_ID) REFERENCES SOIP_Departamentos(SOIP_Departamentos_ID), 
    UNIQUE (EXTRACT (MONTH FROM TIMESTAMP fecha), EXTRACT(YEAR FROM TIMESTAMP fecha)) 
) 

任何想法,我怎麼能做到這一點,沒有具體的年和月列?

謝謝。

回答

3

一個快速的解決方法:

create unique index on adempiere.SOIP_Deudas (EXTRACT (MONTH FROM fecha), EXTRACT(YEAR FROM fecha)); 
+0

工作就像一個魅力,謝謝。 – Uri

+2

這個可能稍微快一點的變化就是在'(date_trunc('month',fecha))'上編制索引。 http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC – kgrittn

+1

@kgrittn或者:'date_trunc('month',fecha):: date',因爲'datetrunc( )'返回一個時間戳,我們只需要一個日期(8比4字節 - >索引大小)。但是,由於[數據對齊和填充,保存的4個字節會浪費](http://stackoverflow.com/a/7431468/939860),除非在索引中有其他列。 –

相關問題