我在Postgres有一个表格定义。我想向字符数据类型为只有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‘作为值。
我在哪里能找到关于这个的一些文件?
发布于 2015-06-15 12:26:22
使用check约束:
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
发布于 2015-06-15 12:34:07
如果您想在不改变条件的情况下添加字符:
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表中的值。
https://stackoverflow.com/questions/30845055
复制相似问题