我正在尝试创建组件层次结构,fx。:
CREATE TABLE COMPONENTS(id, name, price, component_type)
CREATE TABLE SUB_COMPONENTS_1(...)
CREATE TABLE SUB_COMPONENTS_2(...)
SUB_COMPONENTS表使用超类型的id列作为外键,并且根据它是什么component_type来“填充”它们。 (即component_type列)
我一直在努力追随: http://bytes.com/topic/sql-server/answers/808389-design-question-type-heirarchy-supertype-queries 但是无法理解他如何制作“vehicle_type”UNIQUE,并且能够在车辆表中创建具有相同“vehicle_type”的多个条目?
任何帮助理解这一点,将不胜感激!
更新:
没有关系的关系模式就我所说的而言:
组件(component_id:serial,name:string,type:string,price:double)
轮子(wheel_id = component_id,kind:string,price = component_price)
Motor(motor_id = component_id,kind:string,price = component_price)
汽车(名称:字符串,total_price,wheels = component_id,motor = component_id ....)
答案 0 :(得分:1)
要回答您关于了解您发布的链接中发生了什么的问题,示例并不是说vehicle_type
是唯一的,而是说vin
的组合 }和vehicle_type
是唯一的。该示例使用这两列的组合作为键。但是,我建议使用显式id作为键(例如ComponentID
将是Components
表上的主键和每个子组件表上的外键。)如下所示:
CREATE TABLE Components
(
ComponentID int identity(1,1) not null,
// Other columns here
CONSTRAINT [PK_ComponentID] PRIMARY KEY CLUSTERED
(
[ComponentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
)
CREATE TABLE SubComponents1
(
SubComponent1ID int identity(1,1) not null,
ComponentID int not null,
// Other columns here
CONSTRAINT [PK_SubComponent1ID] PRIMARY KEY CLUSTERED
(
[SubComponent1ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
)
GO
ALTER TABLE SubComponents1 WITH NOCHECK ADD CONSTRAINT [FK_SubComponents1_Components] FOREIGN KEY(ComponentID)
REFERENCES Components (ComponentID)
GO
ALTER TABLE SubComponents1 CHECK CONSTRAINT [FK_SubComponents1_Components]
GO
如果你能更好地解释一下你的问题是什么(以及你的子表的模式),我会推荐这个答案,以包含与你的问题有关的更多细节。
答案 1 :(得分:1)
要实现这一目标,您只需要两个表
CREATE TABLE COMPONENTS(id,component_type)
CREATE TABLE SUB_COMPONENTS(s_id,name,Price)
ID Component_Type
1米格
2 SU
SUB_COMPONENT contains s_id as foreign key So the table values will be
1 MIG $ 30
1 MIG-15 $ 20
1 MIG-17 $ 30
2 SU-25 $ 30
2 SU-25 $ 20
您可以在sub_Components表中包含所需数量的子类型和价格。
您可以通过此查询获得结果
SELECT * FROM SUB_COMPONENTS,其中s_id = 1(FOR MIG类型或2代表SU类型)
或者按名称连接表和订单您将获得层次结构中的列表。
根据我的理解,我希望这会回答你的问题。