增加几行唯一价值

时间:2018-09-18 12:19:08

标签: sql postgresql sql-update unique-constraint

我将表创建为

create table public.test
(
    val int unique not null
)

此表包含一些行

|   Val  |
|--------|
|1       |
|2       |
|3       |
|4       |
|5       |
|6       |
|7       |
|8       |
|9       |

我想将所有值增加到大于5(使用PostgreSQL)。但是,如果尝试update public.test set val=val+1 where val > 5,我会得到例外:

  

错误:重复的键值违反了唯一约束“ test_val_key”   详细信息:密钥(val)=(7)已经存在。

我该怎么做?

3 个答案:

答案 0 :(得分:3)

如果您定期需要,则应将约束创建为可延期的:

create table test
(
    val int not null
);
alter table test
   add constraint unique_value unique(val)
   deferrable initially immediate;

要使预期的更新生效,就不必在会话中将约束标记为initially deferred或将change the constraints标记为可延期。

在上述约束下,以下更新工作正常:

update test set val=val+1 where val > 5;

在线示例:http://rextester.com/KXI21597

答案 1 :(得分:2)

不带import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { AuthProvider } from '../auth/auth'; import { Issue } from '../../models/issue' @Injectable() export class JiraProvider { apiVersion: string = '2'; // The API version we want to use jiraInstanceUrl: string = 'http://localhost:8089' // The Jira instance URL urlString: string = `${this.jiraInstanceUrl}/rest/api/${this.apiVersion}`; // Concat those together constructor( public http: HttpClient, public auth: AuthProvider ) { } // Authenticate the user against Jira's profile endpoint. public authenticateUser(username: string, password: string): Observable<Object> { return this.http.get(`${this.urlString}/myself`, { headers: new HttpHeaders() .append('Authorization', `Basic ${btoa(username + ':' + password)}`) .append("Access-Control-Allow-Origin","*") }); } // Get issue details based on the provided key. public getIssue(key: string): Observable<Issue> { return this.http.get<Issue>(`${this.urlString}/issue/${key}`, { headers: new HttpHeaders() .append('Authorization', `Basic ${this.auth.getAuthString()}`) .append("Access-Control-Allow-Origin","*") }); } public getAllIssue():Observable<any> { return this.http.get(`${this.urlString}/search?jql=project=PM`,{ headers: new HttpHeaders() .append('Authorization', `Basic ${this.auth.getAuthString()}`) .append("Access-Control-Allow-Origin","*") }); } public postIssue(data):Observable<any>{ return this.http.post(`${this.urlString}/issue`,JSON.stringify(data),{ headers: new HttpHeaders() .append('Authorization', `Basic ${this.auth.getAuthString()}`) .append('Content-Type','application/json') .append("X-Atlassian-Token", "no-check") .append("User-Agent", "xx") .append("Access-Control-Allow-Origin","*") }); } }

的选项
deferrable initially immediate

在线示例:http://rextester.com/HVZRC8695

检查排序是否已保存的在线示例:http://rextester.com/FAU54991

答案 2 :(得分:1)

一种选择是删除唯一约束,然后将其重新添加。

另一个选择是黑客:

update public.test
    set val = - val
    where val > 5;

update public.test
    set val = (- val) + 1
    where val < 0;