如何同时处理 parent/child 关系和属性
How to handle both parent/child relationship and attributes
我正在构建 html 标签和属性的数据库。
ul 标签有一个 li 标签作为 parent/child 关系。
li 标签有一个 'value' 属性,所以它不是真正的 parent/child 关系。 'value' 是属性,不是标签。
您将如何设置 table 结构来处理 parent/child 关系和属性?
create table tag
(tagid int identity primary key
,tagName varchar(max)
)
go
create table prop
(propid int identity primary key
,parentid int
,childid int
)
go
我可以将另一个字段添加到 'prop' table 以确定这是否真的是 parent/child 关系或属性关系:
alter table prop
add typeid int
但我是不是走错了路?
您需要的是三个 table:Tag、TagProperty 和 TagToTagProperty。
- Table 标签保存 Html 标签名称,并带有对父标签的自指向引用。
- TagProperty 包含 Html 标签属性
- TagToTagProperty table 是 Tag 和 TagProperty 之间的链接 table,其中每个标签只能有一个不同的 属性:PRIMARY KEY (TagId, TagPropertyId)
试试下面的代码:
CREATE TABLE Tag (
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(126),
ParentTagId INT NULL
)
GO
CREATE TABLE TagProperty
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(126)
)
CREATE TABLE [dbo].[TagToTagProperty](
[Id] [int] IDENTITY(1,1) NOT NULL,
[TagId] [int] NOT NULL,
[TagPropertyId] [int] NOT NULL
CONSTRAINT PK_TagToTagProperty_TagId_TagPropertyId PRIMARY KEY (TagId, TagPropertyId)
) ON [PRIMARY]
GO
INSERT INTO TAG (Name, ParentTagId)
VALUES('UL', NULL); --UL tag has no parent therefore ParentId is Null
INSERT INTO TAG (Name, ParentTagId)
VALUES('LI', 1); -- LI tag has a parent therefore parentId is one
INSERT INTO TagProperty (Name)
VALUES ('value')
go
/*
Linking table between tag and attributes
*/
INSERT INTO TagToTagProperty( TagId, TagPropertyId)
VALUES
(1,1),
(1,2)
我正在构建 html 标签和属性的数据库。 ul 标签有一个 li 标签作为 parent/child 关系。 li 标签有一个 'value' 属性,所以它不是真正的 parent/child 关系。 'value' 是属性,不是标签。
您将如何设置 table 结构来处理 parent/child 关系和属性?
create table tag
(tagid int identity primary key
,tagName varchar(max)
)
go
create table prop
(propid int identity primary key
,parentid int
,childid int
)
go
我可以将另一个字段添加到 'prop' table 以确定这是否真的是 parent/child 关系或属性关系:
alter table prop
add typeid int
但我是不是走错了路?
您需要的是三个 table:Tag、TagProperty 和 TagToTagProperty。
- Table 标签保存 Html 标签名称,并带有对父标签的自指向引用。
- TagProperty 包含 Html 标签属性
- TagToTagProperty table 是 Tag 和 TagProperty 之间的链接 table,其中每个标签只能有一个不同的 属性:PRIMARY KEY (TagId, TagPropertyId)
试试下面的代码:
CREATE TABLE Tag (
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(126),
ParentTagId INT NULL
)
GO
CREATE TABLE TagProperty
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(126)
)
CREATE TABLE [dbo].[TagToTagProperty](
[Id] [int] IDENTITY(1,1) NOT NULL,
[TagId] [int] NOT NULL,
[TagPropertyId] [int] NOT NULL
CONSTRAINT PK_TagToTagProperty_TagId_TagPropertyId PRIMARY KEY (TagId, TagPropertyId)
) ON [PRIMARY]
GO
INSERT INTO TAG (Name, ParentTagId)
VALUES('UL', NULL); --UL tag has no parent therefore ParentId is Null
INSERT INTO TAG (Name, ParentTagId)
VALUES('LI', 1); -- LI tag has a parent therefore parentId is one
INSERT INTO TagProperty (Name)
VALUES ('value')
go
/*
Linking table between tag and attributes
*/
INSERT INTO TagToTagProperty( TagId, TagPropertyId)
VALUES
(1,1),
(1,2)