PostgreSQL约束-仅一行可以设置标志 [英] PostgreSQL constraint - only one row can have flag set

查看:71
本文介绍了PostgreSQL约束-仅一行可以设置标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PostgreSQL表

I have a PostgreSQL table

CREATE TABLE my_table
(
  id serial NOT NULL,
  name text,
  actual boolean DEFAULT false,
  CONSTRAINT my_table_pkey PRIMARY KEY (id),
);

如何设置一个约束,使只有一行可以具有 actual 标志设置为 TRUE

How can I set a constraint that only one row can have actual flag set to TRUE?

推荐答案

您可以在该列上仅为真值创建唯一索引:

You can create a unique index on that column only for true values:

create unique index on my_table (actual) 
where actual = true;

SQLFiddle: http://sqlfiddle.com/#!15/91f62/1

SQLFiddle: http://sqlfiddle.com/#!15/91f62/1

这篇关于PostgreSQL约束-仅一行可以设置标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆