POSTGRES - 仅在填写某列时插入

时间:2017-07-05 19:05:54

标签: sql database postgresql

有:

ID start_date  end_date     account 
1   2016-06-30  null         123
1   2017-04-19  null         111
1   2017-04-26  2017-07-30   789

想要完成:

有没有办法创建一个约束/索引/其他机制来检查:

  1. 如果存在ID和帐户且结束日期为空 - >什么都不做
  2. 如果存在ID和帐户且结束日期不为空 - >插入行
  3. 所以:

    insert into table (ID, start_date, account) values (1,2016-08-01,123) 
    

    - >什么都不发生

    insert into table (ID, start_date, account) values (1,2017-04-26, 789)
    

    - >插入行

    我在考虑可能是一个带有存储函数的CHECK约束,它会检查上面的那个或类似的东西?或索引:

    create unique index unique_account on table (ID, account) where end_date is null
    

1 个答案:

答案 0 :(得分:0)

这是最佳实践

警告:在高度事务数据库中使用触发器会导致性能问题。

解决方案:我假设你使用PostgreSQL 9.5或以上

直到这一步你差不多完成了

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
    factory.setReadTimeout(2000);
    factory.setConnectTimeout(2000);
    return factory;
}}
The x

您所要做的就是在PostgreSQL 9.5或更高版本中使用<bean class="org.springframework.web.client.RestTemplate"> <constructor-arg> <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory" p:readTimeout="2000" p:connectTimeout="2000" /> </constructor-arg> 查询

ANS CASE 1:

create unique index unique_account on table (ID, account) where end_date is null

*我们需要UPSERT的唯一索引。此查询意味着如果您插入相同的Insert into insert_only (ID, start_date, account) values (1,'2016-08-01',123) ON CONFLICT DO NOTHING; ,那么"CONFLICT"将会执行id + acoount + date is null

ANS CASE 2:

"ON CONFLICT"

*使用相同的查询,我们在帐户DO NOTHING上输入Insert into insert_only (ID, start_date, end_date,account) values (1,'2016-08-01','2016-08-01',789) ON CONFLICT DO NOTHING; 值,插入就会成功。

<强>输出:

end_date