2013-01-21 91 views
1

我正在爲一家公司的假想車隊開發數據庫模型。有4種類型的車輛(轎車,卡車,半卡車和公共汽車)和2種類型的司機。這兩種車型一次只能駕駛一輛車,第一類車輛只能駕駛車輛,第二類車輛每天只能駕駛一輛車。根據類型的相關表問題

我有我的ER模型設置方式,類型1和類型2從驅動程序表繼承,而車輛類型從車輛表繼承。我的問題在於我可以根據車型的不同將司機連接到他們特定的車輛表。

回答

0

搭建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 diagram

+0

這是非常詳細和有益的,謝謝! – iVikD

0

它看起來像你在考慮OOP而不是關係型數據庫。關係數據庫並不真正支持面向對象的概念,如繼承。我會爲司機和車輛提供一張桌子。關於哪些駕駛員可以駕駛哪些車輛是業務邏輯的規則應該在代碼中進行定義。

擁有多個車輛表和多個驅動程序表將會使得使用數據庫非常困難。

+0

,是有沒有辦法讓它是有條件的,如果我改變的類型,從表中的屬性? – iVikD