SQL优化的问题,高手请入!!

gogogoo 2006-01-25 01:24:13
目前在处理问题时,发现以下两条SQL语句
1、
select a.* from wenjian_recive a,bcbs_gongwen b where a.a3='zhangsan' and ((not length(a.att2)>0) or (not a.att2=a.a3)) and a.a5=0 and a.n3 in (2,3) and '1114853495640'=(select bcbs_gongwen.att1 from bcbs_gongwen where bcbs_gongwen.id=a.qid) order by a.id desc
2、
select a.* from wenjian_recive a,bcbs_gongwen b where a.a3='lisi' and ((not lengt(a.att2)>0) or (not a.att2=a.a3)) and a.a5=0 and a.n3 in (2,3) and '1114853495640'=(select bcbs_gongwen.att1 from bcbs_gongwen where bcbs_gongwen.id=a.qid) order by a.id desc
在执行时有明显的速度差异,其中第一条表现的很慢(约60s)。
请问各位sql高手:这主要是由于什么原因造成的?
在组织and从句时该遵循什么样的原则,是条件越严格的放在越前面吗?
欢迎大家多多讨论!
...全文
220 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zlp321002 2006-01-25
  • 打赏
  • 举报
回复
--建议楼主,好好利用查询计划,分析资源消耗,表扫描情况,索引利用情况,针对性去优化.
--有一些常用的SQL写法也要注意,避免查询丢失索引的写法.
pbsql 2006-01-25
  • 打赏
  • 举报
回复
SQL的写法要规范:
not length(a.att2)>0写成:len(a.att2)=0
not a.att2=a.a3写成:a.att2<>a.a3
'1114853495640'=(select bcbs_gongwen.att1 from bcbs_gongwen where bcbs_gongwen.id=a.qid)换成exists

如下:
select a.*
from wenjian_recive a,bcbs_gongwen b
where a.a3='zhangsan' and ((len(a.att2)=0) or (a.att2<>a.a3))
and a.a5=0 and a.n3 in (2,3)
and exists(select * from bcbs_gongwen
where bcbs_gongwen.id=a.qid and bcbs_gongwen.att1='1114853495640')
order by a.id desc
WangZWang 2006-01-25
  • 打赏
  • 举报
回复
你在a3字段上应该没有建立索引而引起了全表扫描,
当过滤条件不同,查询的可能有些差异,有的马上
就扫描到,而有的要扫描到表尾才能找到。
建议LZ建立索引,和把or条件的分两条语句写
用union all来连组合。

34,838

社区成员

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

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