【问题标题】:How to handle both parent/child relationship and attributes如何处理父/子关系和属性
【发布时间】:2016-04-03 12:57:50
【问题描述】:

我正在构建一个包含 html 标记和属性的数据库。 ul 标签有一个 li 标签作为父/子关系。 li 标签有一个“值”属性,所以它不是真正的父/子关系。 'value' 是一个属性,而不是一个标签。

您将如何设置表结构来处理父/子关系以及属性?

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”表中添加另一个字段,以确定这是真正的父/子关系还是属性关系:

alter table prop
add typeid int

但我是不是走错了路?

【问题讨论】:

    标签: sql-server relational-database


    【解决方案1】:

    您需要三个表:Tag、TagProperty 和 TagToTagProperty。

    1. Table Tag 包含 Html 标记名称以及对父标记的自指向引用。
    2. TagProperty 保存 Html 标签属性
    3. TagToTagProperty 表是 Tag 和 TagProperty 之间的链接表,其中每个标签只能有一个不同的属性: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)
    

    【讨论】:

    • 谢谢@ErnestoDeLaRuiz! Q:怎么知道“value”是属性,而li是孩子?
    • 上面的 LI 记录的 ParentTagId 等于 1。这意味着如果您在 Id 字段的同一个表中查找数字 1,您将找到它的父项。另一方面,TagProperty 表只保存属性,而“值”是多个标签共享的属性。所以你需要一个链接表。 TagToTagProperty 将 Tag Id 与 TagPropertyId 链接起来。
    • 哦,我明白了。您已经为父/子关系添加了一个字段,并为标签/属性关系添加了另一个字段。好的。谢谢!
    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2014-10-30
    • 2021-09-25
    • 2021-03-08
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多