我有两张桌子(完全愿意在规划阶段更改这些表格):
create table building (
buildingId integer primary key autoincrement,
buildingName text
);
create table rooms (
roomId integer primary key autoincrement,
buildingId integer,
FOREIGN KEY(buildingId) REFERENCES building(buildingId)
);
一些当前的样本数据:
building table:
buildingId - buildingName
1 - "house1"
2 - "house2"
rooms table:
roomId - buildingId
1 - 1
2 - 1
3 - 1
4 - 2
5 - 2
对于与建筑有“孩子”关系的房间桌子,每个建筑物都有办法,我重新启动房间的自动增量#?例如,我想要的是以下内容:
rooms table:
roomId - buildingId
1 - 1
2 - 1
3 - 1
1 (changed)- 2
2 (changed)- 2
虽然自动增量为所有建筑物中的每个房间增加了一个独特的id,但是建筑物可以拥有房间4和如第一个样本数据所示,但是没有1到3。
答案 0 :(得分:3)
可以使roomId
列非唯一,以便主键现在包含两列:
create table rooms (
roomId integer,
buildingId integer,
PRIMARY KEY(roomId, buildingId),
FOREIGN KEY(buildingId) REFERENCES building(buildingId)
);
但是,除非您有一个PK列,否则SQLite无法自动分配数字。
请注意,在您的情况下,这似乎是更正确的行为:您希望房间号码与门牌上写的号码相同,而不是数据库分配的一些随机值,因此您需要明确无论如何插入正确的房间号。