2

我正在为一家公司的假设车队开发数据库模型。有 4 种车辆(汽车、卡车、半卡车和公共汽车)和 2 种驾驶员。两种类型一次只能驾驶一辆车,类型 1 只驾驶汽车,类型 2 每天可以驾驶任何一辆车。

我的 ER 模型设置为类型 1 和类型 2 是从 Driver 表继承的,而 4 种车辆类型是从 Vehicle 表继承的。我的问题在于我可以根据司机的类型将司机连接到他们的特定车辆表的方式。

4

2 回答 2

1

设置VehicleTypesVehicles

CREATE TABLE VehicleType
( VehicleTypeID CHAR(1) NOT NULL
, VehicleTypeName VARCHAR(20) NOT NULL
, PRIMARY KEY (VehicleTypeID)
, UNIQUE (VehicleTypeName)
) ;

INSERT INTO VehicleType
  (VehicleTypeID, VehicleTypeName)
VALUES
  ('C', 'Car'),
  ('T', 'Truck'),
  ('S', 'Semi-truck'),
  ('B', 'Bus') ;

CREATE TABLE Vehicle
( VehicleID INT IDENTITY(1,1)
, VehicleTypeID CHAR(1) NOT NULL
, LicencePlate VARCHAR(20) NOT NULL
--- other stuff about a vehicle
, PRIMARY KEY (VehicleTypeId, VehicleID)
, UNIQUE (LicencePlate) 
, FOREIGN KEY (VehicleTypeId)
    REFERENCES VehicleType (VehicleTypeId)
) ;

DriverTypesDrivers:_

CREATE TABLE DriverType
( DriverTypeID INT NOT NULL
, DriverTypeTitle VARCHAR(20) NOT NULL
, PRIMARY KEY (DriverTypeID)
, UNIQUE (DriverTypeTitle)
) ;

INSERT INTO DriverType
  (DriverTypeID, DriverTypeTitle)
VALUES
  (1, 'Driver-Type-1'),
  (2, 'Driver-Type-2') ;

CREATE TABLE Driver
( DriverID INT IDENTITY(1,1) NOT NULL
, DriverTypeID INT NOT NULL
, FullName VARCHAR(40) NOT NULL
--- other stuff about a driver
, PRIMARY KEY (DriverTypeID, DriverID)
, FOREIGN KEY (DriverTypeID)
    REFERENCES DriverType (DriverTypeID)
) ;

最后是各种类型的司机可以驾驶的车辆类型:

CREATE TABLE Driver_Vehicle_Combinations
( DriverTypeID INT NOT NULL
, VehicleTypeID CHAR(1) NOT NULL
, PRIMARY KEY (DriverTypeID, VehicleTypeID)
, FOREIGN KEY (DriverTypeID)
    REFERENCES DriverType (DriverTypeID)
, FOREIGN KEY (VehicleTypeId)
    REFERENCES VehicleType (VehicleTypeId)
) ;

INSERT INTO Driver_Vehicle_Combinations
  (DriverTypeID, VehicleTypeID)
VALUES
  (1, 'C'),
  (2, 'C'),
  (2, 'T'),
  (2, 'S'),
  (2, 'B') ;

如果您还想存储在特定日期实际驾驶哪辆车的人:

CREATE TABLE Driver_Schedule
( DriverID INT NOT NULL
, DriverTypeID INT NOT NULL
, ScheduleDate DATE NOT NULL
, VehicleID INT NOT NULL
, VehicleTypeID CHAR(1) NOT NULL
, PRIMARY KEY (DriverID, ScheduleDate)
, UNIQUE (VehicleID, ScheduleDate)         --- If a vehicle is allowed to be
                                           --- driven by only one driver each day
, FOREIGN KEY (DriverTypeID, DriverID)
    REFERENCES Driver (DriverTypeID, DriverID)
, FOREIGN KEY (VehicleTypeId, VehicleID)
    REFERENCES Vehicle (VehicleTypeId, VehicleID)
, FOREIGN KEY (DriverTypeID, VehicleTypeId)      --- this ensures than no driver
    REFERENCES Driver_Vehicle_Combinations       --- gets to drive a vehicle that
              (DriverTypeID, VehicleTypeId)      --- is not allowed to
) ;

您可以在SQL-Fiddle测试代码。ER 图如下所示:

ER图

于 2013-01-21T17:28:09.177 回答
0

看起来您正在考虑 OOP 而不是关系数据库。关系数据库并不真正支持面向对象的概念,例如继承。我会为司机准备一张桌子,为车辆准备一张桌子。关于哪些司机可以驾驶哪些车辆的规则是业务逻辑,应该在代码中定义。

拥有多个车辆表和多个驾驶员表将使使用数据库变得非常困难。

于 2013-01-21T16:37:12.247 回答