如何更好地设计这个表?

How to design this tables better?

首先,很抱歉我找不到更好的标题。

我有一个数据库,根据设备的数量存储一些设备:

|-----------|-------------|-------------|
| device_id | device_name | device_type |
|-----------|-------------|-------------|

每个设备有两种类型,3-port1-port,每个端口都有特定的名称,例如:

我的想象设计是:

|-----------|-------------|--------|-----------|--------|
+ device_id | device_name | port_1 |  port_2   | port_3 +
|-----------|-------------|--------|-----------|--------|
| 1122      | First floor | kitchen|living_room|bed_room|
|-----------|-------------|--------|-----------|--------|
| 1123      | Second floor| boiler | null      | null   |
|-----------|-------------|--------|-----------|--------|

但我的设计并不好,因为如果我有 100 个类型为 1-port 的设备,我会将 200 个字段留空。 你能帮我创造更好的设计吗?

完全规范化的架构将具有设备类型 table(您在其中为每种设备类型指定端口数),
具有唯一设备名称和设备 ID 的设备 table,
具有唯一端口名称和唯一端口 ID 的端口 table,
以及一个包含设备 ID 和端口 ID 的交集 table,其中这两列的组合是主键。
您应该考虑在向交集添加记录时添加检查约束 table 以确保您不会根据设备类型添加太多记录(如果您的目标数据库支持检查约束)。

这是此架构的伪代码:

TblDeviceType
(
    DeviceType_Id int, -- primary key
    DeviceType_Name varchar(20) -- unique
)

TblDevice
(
    Device_Id int, -- primary key
    Device_Type int, -- fk to TblDeviceType
)

TblPorts
(
    Port_Id int, -- primary key
    Port_Name varchar(30) -- unique
)

TblDeviceToPort
(
    DeviceToPort_Device int, -- fk to TblDevice
    DeviceToPort_Port int, -- fk to TblPort
    Primary key (DeviceToPort_Device, DeviceToPort_Port)
)

我将我的评论粘贴为答案,这样您就可以将问题标记为已回答。

You could break out ports to a separate, normalized table with deviceId, port number, and port name. You will have one record for each device and port combination with a foreign key reference back to the main devices table. This will reduce empty fields and allow more than 3 ports should the requirements change. However this comes at the cost of an additional table and duplication of the key. From a space perspective you may not end up much better. Then again, storage is pretty cheap so I would not sweat it too much.

Zohar 的回答要完整得多,所以如果您接受他的回答,我不会有任何问题。但是你应该接受一个答案来关闭问题。