Sql Postgres函数获取唯一约束冲突
我有一个Sql Postgres函数获取唯一约束冲突,sql,postgresql,plpgsql,Sql,Postgresql,Plpgsql,我有一个plpgsql函数,其中包含 update allplaces set visittime = now() where visittime is null and person = 'me' and place = 'this'; if (FOUND) then update allplaces set visittime = null where person = 'me' and place != 'this'; return true; else retur
plpgsql
函数,其中包含
update allplaces set visittime = now() where visittime is null and person = 'me' and place = 'this';
if (FOUND) then
update allplaces set visittime = null where person = 'me' and place != 'this';
return true;
else
return false;
end if;
allplaces
表有一个唯一的约束,即create unique index indexallplaces on allplaces(person),其中visittime不为null
,这意味着给定的person
只能有一条visittime不为null的记录
我正在尝试将访问时间
从我以前的记录(个人
等于我
)切换到位置
等于这个
)的记录,但是我得到了我提到的唯一索引的唯一约束冲突。我无法将旧值设置为null而不更改以确保已设置新值,因此需要进行if(FOUND)
检查
如何将此postgres功能更改为工作状态?该函数正在使用plpgsql
,但如果在这种情况下效果更好,它也可能是普通SQL
编辑
将查询更改为使用这样的案例如何
update allplaces
set visittime = case when place <> 'this' then null else now() end
where person = 'me';
更新所有位置
设置visittime=放置“this”时的大小写,然后为null else now()结束
其中person='me';
这将使用null更新所有visittimes,但place=This的visittimes除外。
如果在更新时只有一行(me,This),这应该可以工作不幸的是,查询可能会引发重复的键错误。如果在更新时有2+行(me,This),任何查询都会引发异常。你的意思是即使只有一排,它仍然可以提高它?编辑:或者我没有正确计算约束的“NOTNULL”部分。问题是该表被一个部分唯一索引约束,并且可能包含多行
person
和nullvisittime
。
update allplaces
set visittime = case when place <> 'this' then null else now() end
where person = 'me';