请问这句sql查询语句怎么优化?

acdacd 2007-12-01 10:24:56
部门表中,假设本级部门的ID=211,则下级部门及本级部门的所有id通过如下函数取得(各id用英文的逗号分割):
GetAllChildID(211)


现在的问题是:
如果得到的下级部门的id很多(>60),如:211,293,295,296,297,298,299,300,301,302,304,719,499,502,504,728,576,773,776,491,257,732,286,306,308,309,312,313,315,316,317,318,319,320,287,492,493,494,495,496,497,498,500,501,503,734,733,505,506,507,508,509,510,515,516,517,518,511,514,288,289,290,291,292
那么,以下的查询语句将很慢(table表中有百万条数据)
select * from [table] where bm_id in (GetAllChildID(211))
有更好的方法吗?
网上查了下说用 EXISTS 代替 in ,可语句怎么写呢?效果有提升吗?
...全文
109 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
acdacd 2007-12-02
  • 打赏
  • 举报
回复
谢谢!你说的我无法理解。
select * from [table] where bm_id in (GetAllChildID(211)) 怎么优化?
部门表取出部门的id没问题,关键是取出来的id到数据表(table)中匹配查询咋优化?
acdacd 2007-12-02
  • 打赏
  • 举报
回复
select * from [table] where bm_id in (GetAllChildID(211)) 是在asp里面,怎么不可以呢?
Lyw110 2007-12-02
  • 打赏
  • 举报
回复
我觉得这种问题还是优化数据库表好点,找写有关树形的数据库设计,表设计方案好,以后管理起来就方便,查询也简单
中国风 2007-12-02
  • 打赏
  • 举报
回复
use test
go
create table ta (项目 varchar(20),上级项目 varchar(20),num int)
insert ta
select 'A','' ,100 union all
select 'B','A' ,200 union all
select 'C','B' ,300 union all
select 'D','B' ,400 union all
select 'E','C' ,500 union all
select 'F','D' ,600 union all
select 'H','E' ,700 union all
select 'G','F' ,800
go
create function roy_f2(@项目 varchar(20))
returns @tb table(项目 varchar(20),上级项目 varchar(20),num int,lev int)
as
begin
declare @i int,@sum int
set @i=0
insert @tb select *,@i from ta where 项目=@项目
while @@rowcount>0
begin
set @i=@i+1
insert @tb
select a.*,@i
from ta a,@tb b
where b.项目=a.上级项目 and b.lev=@i-1
end
return
end


go
select 项目,上级项目,num from roy_f2('A')

项目 上级项目 num
-------------------- -------------------- -----------
A 100
B A 200
C B 300
D B 400
E C 500
F D 600
H E 700
G F 800

(所影响的行数为 8 行)

这样直接返回下级的结果集
duanzhi1984 2007-12-02
  • 打赏
  • 举报
回复
你的语法是有问题的~~~~~~~
Limpire 2007-12-02
  • 打赏
  • 举报
回复
select * from [table] where bm_id in (GetAllChildID(211))
---------
可以这样吗?忽悠吧
中国风 2007-12-01
  • 打赏
  • 举报
回复
用表函数据直接返回结果集:
中国风 2007-12-01
  • 打赏
  • 举报
回复
列子:
http://blog.csdn.net/roy_88/archive/2006/12/24/1458449.aspx

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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