2017-07-28 84 views
0

我有一個名爲AQI,與下面的列 enter image description here唯一約束鍵不調用

只有一個獨特價值datepollutant_codesource_idtime能夠存在表,所以我定義了一個唯一的約束條件source_code_time_uq

而像

INSERT INTO aqi(source_id, source_type, pollutant_code, "date", "time", aqi_value) 
VALUES (4, 1 ,'PM2.5','2018-05-28',8, 789) 
ON CONFLICT ON CONSTRAINT source_code_time_uq 
DO UPDATE SET 
    aqi_value = 789 

的UPSERT查詢的UPSERT方法,正常工作時,所有的現場可用的,但是當我在time柱放NULL(在企圖使該行代表一個整體AQI數據日),source_code_time_uq約束不會被調用,並且它仍會插入一個新行。

那麼如何在字段上添加唯一的約束檢查,也可以是NULL,我需要更新我的upsert查詢嗎?

+0

這是真正的SQL Server?語法看起來不像。 –

回答

1

您可以使用篩選唯一索引:

create unique index unq_aqi_4 on (date, pollutant_code, source_id, time) 
    where time is not null; 

然後,你可能也想保證每天只有一個NULL行,所以:

create unique index unq_aqi_4 on (date, pollutant_code, source_id) 
    where time is null; 

當然,除去unique約束以及。

0

與唯一約束的問題是,它將使一個空,所以我們可能要爲定義列不爲空。希望這有助於