高手帮忙,一个小树的查询.(有点难)

cowbo2 2006-09-30 10:27:56

是这样的...
就是表Products 中的字段DepartId是部门编号,对应到 部门表Depart(3级树结构)的 DID(此为自动编号) 中,请问,当给出一个部门的名称时,如何查询出表Products中的该编号及其下级的记录?

难点:
1.查询出对应编号及下级记录.
2.有没办法用一条SQL语句.


表Depart

DID Name1 ParentID Leave
------------------------------------
39 上海公司 0 1
40 北京公司 0 1
47 电脑部 40 2
48 工程部 39 2
49 电脑1部 47 3
50 电脑2部 47 3
51 工程1部 48 3
52 工程2部 48 3
75 香港公司 0 1
....


表Products

Pid Pcode DepartID(此编号记录全为最底层)
-----------------------
1 BA-0001 49
2 DE-0002 51
3 HE-0001 75




...全文
208 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuynalei 2006-10-05
  • 打赏
  • 举报
回复
试试这个
select * from products a where not exists (select * from products where parentid=t.did)
kingmax54212008 2006-10-05
  • 打赏
  • 举报
回复
select products.Pcode,D.Name1,D.subdepart1,d.subdepart2
from products
left join
(select A.DID,A.Name1,B.DID as subid1,B.Name1 as subdepart1,c.DID as subid2,C.Name1 as subdepart2
from depart A
left join depart B
on B.ParentID = A.DID
left join depart C
on C.ParentID = B.DID) as D
on products.departID in(D.DID,D.subid1,D.subid2)
where D.name1 = '部门名称' --- ‘部门名称' 为你要查询的部门

以上SQL语句测试通过,楼主试一下~~~
kingmax54212008 2006-10-05
  • 打赏
  • 举报
回复
楼上的SQL句中表Depart呢?
liuynalei 2006-10-05
  • 打赏
  • 举报
回复
不好意思写错了,应该是
select * from products t where not exists (select * from products where parentid=t.did)
kingmax54212008 2006-10-05
  • 打赏
  • 举报
回复
t是什么?我试了.运行不通过~~~
楼上再解释一下
ThankSZ 2006-10-01
  • 打赏
  • 举报
回复
楼主是不是想生成一棵树呀?
cowbo2 2006-09-30
  • 打赏
  • 举报
回复


楼上,我的是SQL的啊...而且是ACCESS..能不能用你这个?
allright_flash 2006-09-30
  • 打赏
  • 举报
回复
摆渡一下
start with ...connect by ...

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧