您可以创建三个单独的表:SpeedboatTests,CarTests和GokartTests。但是很多列在每个表中都是相同的(例如,执行测试的人员的员工ID,碰撞的方向(正面,侧面,后面)等)。但是,很多列都会有所不同,因此您不希望将所有测试数据放在一个表中,因为您将拥有相当多的列,对于快艇来说总是为空,相当多的列总是如此对于汽车来说是零,而对于卡丁车来说,相当多的都是空的。
假设您还想存储一些与测试没有直接关系的信息(例如正在测试的东西的设计者的员工ID)。这些列根本不适合放入“测试”表,特别是因为它们将在同一车辆上的所有测试中重复出现。
让我说明一种可能的表格排列,以便您可以看到所涉及的问题。
Speedboats id | col_about_speedboats_but_not_tests1 | col_about_speedboats_but_not_tests2 Cars id | col_about_cars_but_not_tests1 | col_about_cars_but_not_tests2 Gokarts id | col_about_gokarts_but_not_tests1 | col_about_gokarts_but_not_tests2 Tests id | type | id_in_type | col_about_all_tests1 | col_about_all_tests2 (id_in_type will refer to the id column of one of the next three tables,depending on the value of type) SpeedboatTests id | speedboat_id | col_about_speedboat_tests1 | col_about_speedboat_tests2 CarTests id | car_id | col_about_car_tests1 | col_about_car_tests2 GokartTests id | gokart_id | col_about_gokart_tests1 | col_about_gokart_tests2
这个结构的优点/缺点是什么,实现这样的优先方式是什么?
如果还有一些信息适用于您希望在车辆表中使用的所有车辆,该怎么办?那么CarTests表会看起来像……
id | vehicle_id | ... With a Vehicles table like this: id | type | id_in_type (with id_in_type pointing to the id of either a speedboat,car,or go-kart)
这似乎是一场皇家般的混乱。应该如何设置这样的东西?
解决方法
这是定义表的更好方法:
>制作抽象表车辆为所有车辆子类型和车辆测试提供抽象参考点。
>每个车辆子类型都有一个不会自动递增的主键,而是引用车辆。
>每个测试子类型都有一个不会自动递增的主键,而是引用测试。
>每个测试子类型也具有相应车辆子类型的外键。
这是DDL的示例:
CREATE TABLE Vehicles ( vehicle_id INT AUTO_INCREMENT PRIMARY KEY ); CREATE TABLE Speedboats ( vehicle_id INT PRIMARY KEY,col_about_speedboats_but_not_tests1 INT,col_about_speedboats_but_not_tests2 INT,FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id) ); CREATE TABLE Cars ( vehicle_id INT PRIMARY KEY,col_about_cars_but_not_tests1 INT,col_about_cars_but_not_tests2 INT,FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id) ); CREATE TABLE Gokarts ( vehicle_id INT PRIMARY KEY,col_about_gokarts_but_not_tests1 INT,col_about_gokarts_but_not_tests2 INT,FOREIGN KEY(vehicle_id) REFERENCES Vehicles(vehicle_id) ); CREATE TABLE Tests ( test_id INT AUTO_INCREMENT PRIMARY KEY,col_about_all_tests1 INT,col_about_all_tests2 INT ); CREATE TABLE SpeedboatTests ( test_id INT PRIMARY KEY,vehicle_id INT NOT NULL,col_about_speedboat_tests1 INT,col_about_speedboat_tests2 INT,FOREIGN KEY(test_id) REFERENCES Tests(test_id),FOREIGN KEY(vehicle_id) REFERENCES Speedboats(vehicle_id) ); CREATE TABLE CarTests ( test_id INT PRIMARY KEY,col_about_car_tests1 INT,col_about_car_tests2 INT,FOREIGN KEY(vehicle_id) REFERENCES Cars(vehicle_id) ); CREATE TABLE GokartTests ( test_id INT PRIMARY KEY,col_about_gokart_tests1 INT,col_about_gokart_tests2 INT,FOREIGN KEY(vehicle_id) REFERENCES Gokarts(vehicle_id) );
您也可以声明引用Vehicles.vehicle_id的Tests.vehicle_id并删除每个测试子类型表中的vehicle_id外键,但这将允许异常,例如引用gokart id的快艇测试。
原文地址:https://www.jb51.cc/mssql/84453.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。