Postgres SQL 约束一个字符类型

Postgres SQL constraint a character type

我在 Postgres 中有一个 table 定义。我想向字符数据类型的列添加一个约束,使其只有 3 个允许值:

CREATE TABLE my_table
(
  id character varying(255) NOT NULL,
  uid character varying(255) NOT NULL,
  my_text text NOT NULL,
  is_enabled boolean NOT NULL
);

所以我希望 my_text 列仅包含 'A'、'B' 或 'C' 作为值。

我在哪里可以找到这方面的一些文档?

使用检查约束:

CREATE TABLE my_table
(
  id character varying(255) NOT NULL,
  uid character varying(255) NOT NULL,
  my_text text NOT NULL,
  is_enabled boolean NOT NULL,
  constraint check_allowed check (my_text in ('A', 'B', 'C'))
);

手册中有更多详细信息:http://www.postgresql.org/docs/current/static/ddl-constraints.html#DDL-CONSTRAINTS-CHECK-CONSTRAINTS

如果你希望能够在不修改条件的情况下添加字符:

CREATE TABLE my_ref
(
  my_value varying(1) PRIMARY KEY
)

INSERT INTO my_ref VALUES( 'A' );
INSERT INTO my_ref VALUES( 'B' );
INSERT INTO my_ref VALUES( 'C' );

CREATE TABLE my_table
(
  id character varying(255) NOT NULL,
  uid character varying(255) NOT NULL,
  my_text text NOT NULL,
  is_enabled boolean NOT NULL,
  constraint check_allowed FOREIGN KEY( my_text ) REFERENCES my_ref( my_value )
);

您将无法在 my_text 中添加不在 my_ref table.

中的值