数据库设计:我需要数据库中的实体与自身相关,但也要独立

时间:2022-10-04 09:37:27

I am sorry if the title of question is not clear. I will try to explain below:

如果问题的标题不清楚,我很抱歉。我将尝试解释如下:

So I am trying to design a database for a Campus Housing App. The Rooms can be either Single Rooms or Apartments. Apartments are basically 2 separate single rooms that have sequential numbers. Meaning rooms numbered 2135 and 2137 are two single rooms that form an apartment. Whereas room 2149 is just a single room.

所以我正在尝试为Campus Housing App设计一个数据库。客房可以是单人间或公寓。公寓基本上是2个独立的单人房,有序号。编号为2135和2137的意义室是两个单独的房间,形成一个公寓。而2149房间只是一个单间。

My Room entity table has the following fields:

我的房间实体表包含以下字段:

数据库设计:我需要数据库中的实体与自身相关,但也要独立

Am I supposed to add a boolean field IsApartment? But then how can I keep track of which room is connected to the other room that makes up the apartment?

我应该添加一个布尔字段IsApartment吗?但是,我怎样才能跟踪哪个房间连接到组成公寓的另一个房间?

2 个解决方案

#1


1  

You can have 2 different tables - one for single room and another for apartment. Apartment would need 2 columns ( for the 2 single rooms ) and they would act as a composite primary key that would uniquely identify the apartment. You can also define the foreign key from apartment to single_room to ensure that the apartment rooms are definitely single rooms.

您可以拥有2张不同的桌子 - 一张用于单人间,另一张用于公寓。公寓需要2列(对于2个单人间),它们将作为复合主键,可以唯一地识别公寓。您还可以定义从公寓到单人房的外键,以确保公寓房肯定是单人房。

#2


1  

Why not add another table "linkedroom" with fields roomID (JOINed to your room ID) and linkedroomID?

为什么不添加另一个表“linkedroom”与字段roomID(加入你的房间ID)和linkedroomID?

This way you'll have information about the second room if the first one is an apartment, and null if it's not.

这样,如果第一个房间是公寓,您将获得有关第二个房间的信息,如果不是,则为零。

#1


1  

You can have 2 different tables - one for single room and another for apartment. Apartment would need 2 columns ( for the 2 single rooms ) and they would act as a composite primary key that would uniquely identify the apartment. You can also define the foreign key from apartment to single_room to ensure that the apartment rooms are definitely single rooms.

您可以拥有2张不同的桌子 - 一张用于单人间,另一张用于公寓。公寓需要2列(对于2个单人间),它们将作为复合主键,可以唯一地识别公寓。您还可以定义从公寓到单人房的外键,以确保公寓房肯定是单人房。

#2


1  

Why not add another table "linkedroom" with fields roomID (JOINed to your room ID) and linkedroomID?

为什么不添加另一个表“linkedroom”与字段roomID(加入你的房间ID)和linkedroomID?

This way you'll have information about the second room if the first one is an apartment, and null if it's not.

这样,如果第一个房间是公寓,您将获得有关第二个房间的信息,如果不是,则为零。