一对多的关系(这一项由几个子项组合而成 子项又由几个子项...)应该如何建表易于扩展和操作?sqlsever建表

解决方案 »

  1.   

    如果是组织结构方面的,可以这样:--drop table tcreate table t
    (
    id int primary key,
    pid int foreign key references t(id),  --上级id
    v varchar(100)
    )
      

  2.   

    如果是熟的形式的话,你就创建在同一张表表,只需要添加子级id和父级id。
    例如:id  parentid name
    1    null    中国
    2    1       上海
    3    2       普陀区
    4    2       徐汇区
    5    2       浦东区
      

  3.   

    这样呢,试试:
    --drop table tcreate table t
    (
    id int primary key,
    pid int foreign key references t(id),  --上级id
    name varchar(100),
    calc_method varchar(100)
    )
    insert into t
    select 1,null,'工作量'  ,null union all
    select 2,1   ,'理论'    ,null union all
    select 3,2   ,'理论课程','基础工作量100' union all
    select 4,2   ,'实验课程','基础工作量100' union all
    select 5,1   ,'实践'    ,null union all
    select 6,5   ,'课程设计','基础工作量100' union all
    select 7,1   ,'其它'    ,null union all
    select 8,7   ,'论文'    ,'4分/次' union all
    select 9,8   ,'社会实践','3分/次' 
    select t1.name,t2.name,t3.name,t3.calc_method
    from t t1
    inner join t t2
            on t1.id = t2.pid
    inner join t t3
            on t2.id = t3.pid
    where t1.pid is null     
    /*
    name name name calc_method
    工作量 理论     理论课程 基础工作量100
    工作量 理论     实验课程 基础工作量100
    工作量 实践    课程设计 基础工作量100
    工作量 其它   论文     4分/次
    */