首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请教这个树的sql语句该如何写啊一定给分

2012-02-12 
请问这个树的sql语句该怎么写啊,一定给分用户表tb_userinfouseridusernamedepartmentid001ABC001002AAA001

请问这个树的sql语句该怎么写啊,一定给分
用户表  
tb_userinfo

userid       username           departmentid
001                 ABC                     001
002                 AAA                     001
003                 VVV                     002
004                 RRR                     002

部门信息表
tb_departmentinfo

departmentid     deparmentname
001                             A部门
002                             B部门

如何查询出树结构的列表?
象这样
userid       username           departmentid       deparmentname
  null           null                     001                         A部门
    001           ABC                       001                         A部门
    002           AAA                       001                         A部门
    null         null                     002                         B部门
    003           VVV                       002                         B部门
    004           RRR                       002                         B部门

快来人拉,在线等待拉




[解决办法]
if object_id( 'pubs..tb_userinfo ') is not null
drop table tb_userinfo
go
create table tb_userinfo(userid varchar(10),username varchar(10),departmentid varchar(10))
insert into tb_userinfo(userid,username,departmentid) values( '001 ', 'ABC ', '001 ')
insert into tb_userinfo(userid,username,departmentid) values( '002 ', 'AAA ', '001 ')
insert into tb_userinfo(userid,username,departmentid) values( '003 ', 'VVV ', '002 ')
insert into tb_userinfo(userid,username,departmentid) values( '004 ', 'RRR ' , '002 ')
go

if object_id( 'pubs..tb_departmentinfo ') is not null
drop table tb_departmentinfo
go
create table tb_departmentinfo(departmentid varchar(10),deparmentname varchar(10))
insert into tb_departmentinfo(departmentid,deparmentname) values( '001 ', 'A部门 ')


insert into tb_departmentinfo(departmentid,deparmentname) values( '002 ', 'B部门 ')

select * from
(
select userid = null,username = null , * from tb_departmentinfo
union all
select a.userid , a.username , a.departmentid , b.deparmentname from tb_userinfo a,tb_departmentinfo b where a.departmentid = b.departmentid
) t
order by departmentid,userid

drop table tb_userinfo,tb_departmentinfo

/*
userid username departmentid deparmentname
---------- ---------- ------------ -------------
NULL NULL 001 A部门
001 ABC 001 A部门
002 AAA 001 A部门
NULL NULL 002 B部门
003 VVV 002 B部门
004 RRR 002 B部门

(所影响的行数为 6 行)

*/

热点排行