0

我有一种情况,我想要一个包含三个字段的表,一个 ID、一个建筑物名称和一个房间名称。ID 只是一个自动增量,而 Building 不是 NULL。但是房间可以为NULL,但我想安排建筑物和房间的组合是唯一的。这可能吗?我该如何设置?

谢谢,詹姆斯

4

1 回答 1

2

创建一个带unique约束的表:

create table t (id integer primary key,
                building text not null,
                room text,
                unique (building, room));

插入数据:

insert into t (building, room) values ("B1", "R1");
insert into t (building, room) values ("B1", "R2");
insert into t (building, room) values ("B1", null);
insert into t (building, room) values ("B1", "R3");
insert into t (building, room) values ("B1", "R1");
-- Error: columns building, room are not unique
insert into t (building, room) values ("B1", null);
-- Note: This last insert does not violate the constraint!

查看数据:

select * from t;
1|B1|R1
2|B1|R2
3|B1|
4|B1|R3
5|B1|
于 2012-11-02T10:21:09.940 回答