MySQL层级表及表关系

23 阅读1分钟

层级表

  • 闭包模型
电子数码(id=1)
    手机通讯(id=2)
        智能手机(id=3)
        老人机(id=4)
    电脑办公(id=5)

create table Students(
       id int notnull
       uname varchar(1000) not null
)

这个专门存储节点信息,特别是深度层级(这个表主要表达层级关系的)

create table node(
    father_id int not null
    son_id  int not null
    depth int
)

这个sql语句的意思是将id为1的电子数码设置为顶级的祖先id

insert into node(father_id,son_id,depth) value
(1,1,0)
  • 邻接列表模型
电子数码(id=1)
    手机通讯(id=2,parent_id=1)
        智能手机(id=3,parent_id=2)
        老人机(id=4,parent_id=2)
    电脑办公(id=5,parent_id=1)

  • 主要体现在parent_id这个字段
create table Students (
    id int not null
    uname varchar(1000) not null
    parent_id int not null
)
  • 其他的表关系

多对多关系---通常需要一个中间表

一对一关系---通常关联的表需要一个字段与主表的id对应,其中unique表示关系

多对一关系---通常需要一个字段进行关联