表1
user(员工)     dept(部门)
张三             it部
李四             人事科
小王             第一产品科注:人事科属于行政部表2
dept_name(子部门)        dept_parent(主部门)
it部                        it中心 
人事科                      行政部 
行政部                      行政中心
第一产品科                  第一产品软件部
第一产品软件部              第一产品部
第一产品部                  研发中心 
问题是 sql语句怎么写,才能知道这个人属于那个 中心
查出的结果是
user               dept_parent
张三                it中心
李四                行政中心
小王                 研发中心 

解决方案 »

  1.   

    select a.user,a.dept,b.dept_parent
    from tb1 a left join tb2 b
    on a.dept=b.dept_name
      

  2.   

    drop table 表1,表2
    go
    create table 表1([user] varchar(10),dept varchar(20))
    insert into 表1
    select '张三','it部'
    union all select '李四','人事科'
    union all select '小王','第一产品科'create table 表2(dept_name varchar(20),dept_parent varchar(20))
    insert into 表2
    select 'it部','it中心'
    union all select '人事科','行政部'
    union all select '行政部','行政中心'
    union all select '第一产品科','第一产品软件部'
    union all select '第一产品软件部','第一产品部'
    union all select '第一产品部','研发中心'
    go
    create function f_getparent(@dept_name varchar(20))
    returns varchar(20)
    as
    begin
    declare @dept_parent varchar(100)
    select @dept_parent=dept_parent from 表2 where dept_name=@dept_name
    while exists(select 1 from 表2 where dept_name=@dept_parent)
    begin
    select @dept_parent=dept_parent from 表2 where dept_name=@dept_parent
    end
    return @dept_parent
    end
    go
    select [user],dbo.f_getparent(dept) as dept_parent from 表1
    /*
    user       dept_parent          
    ---------- -------------------- 
    张三         it中心
    李四         行政中心
    小王         研发中心(所影响的行数为 3 行)
    */
      

  3.   

    select t1.user,t1.dept,t2.dept_parent
    from 表1 t1 inner join 表2 t2
    on t1.dept=t2.dept_name
      

  4.   

    create function f_getParent(@child varchar(20))
    returns varchar(30)
    as
    begin
        while exists(select 1 from t2 where dept_name=@child and dept_parent<>'')
            select @child=dept_parent from t2 where dept_name=@child
        return @child
    end
    gocreate table t1([user] varchar(20),dept varchar(20))
    insert t1 select '张三','it部'
    union all select '李四','人事科'
    union all select '小王','第一产品科'create table t2(dept_name varchar(30),dept_parent varchar(30))
    insert t2 select 'it部','it中心'
    union all select '人事科','行政部'
    union all select '行政部','行政中心'
    union all select '第一产品科','第一产品软件部'
    union all select '第一产品软件部','第一产品部'
    union all select '第一产品部','研发中心'select [user],dept_parent=dbo.f_getParent(dept) from t1drop table t1,t2
    drop function f_getParentuser                 dept_parent                    
    -------------------- ------------------------------ 
    张三                   it中心
    李四                   行政中心
    小王                   研发中心(所影响的行数为 3 行)