SQlite在两个字段中放置一个唯一的关键字,其中一个字段可能为null

时间:2012-11-02 10:02:28

标签: sqlite

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

谢谢, 詹姆斯

1 个答案:

答案 0 :(得分: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|