效率问题.

zoulipeng 2005-12-16 12:39:28
--表
Create Table T(id int identity(1,1),A int, B datetime)

select
top 1 字段=A from T
where
A<=2000
order by A desc

1:它用exists 语句怎么写?
2:它的效率和exists效率哪一个高?

...全文
155 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
zlp321002 2006-01-03
  • 打赏
  • 举报
回复
--Top 已经被优化的一个关键字,效率应该还是蛮高的.
--子查询才会有 exits 的效率要比 in 的高的问题.
--同意 libin_ftsafe(子陌红尘|潇湘剑公子@dev-club)
子陌红尘 2005-12-16
  • 打赏
  • 举报
回复
应该是等价于如下语句:

select
a.*
from
t a
where
a.A<=2000
and
not exists(select 1 from t where id=a.id and A<=2000 and A>a.A)
子陌红尘 2005-12-16
  • 打赏
  • 举报
回复
通常情况下,用exists()的查询比用in()的查询的效率高,但在楼主设置的这个场景下不具备可比性,楼主的查询可以替换成以下形式,效率不如TOP 1语句。

select
a.*
from
t a
where
not exists(select 1 from t where id=a.id and A<=2000 and A>a.A)
zoulipeng 2005-12-16
  • 打赏
  • 举报
回复
1楼查询结果,都不对......

samfeng_2003 2005-12-16
  • 打赏
  • 举报
回复
select * from t a where exists
(select top 1 * from t b where a.id=b.id and a<=2000 order by A desc)

这样写是多余的,因为本先一句就可以直接得到的结果,用了两个步骤,效率当然不高了!
如果必须的话,那么exists的效率好象要高于IN吧
bugchen888 2005-12-16
  • 打赏
  • 举报
回复
SELECT 字段=MAX(A)
FROM T
WHERE A<=2000

倒排序的第一笔不就是MAX吗,干嘛搞那么复杂?
子陌红尘 2005-12-16
  • 打赏
  • 举报
回复
--表
Create Table T(id int identity(1,1),A int, B datetime)
insert into t select 1900,getdate()
insert into t select 1900,getdate()
insert into t select 1900,getdate()
insert into t select 2015,getdate()
insert into t select 1998,getdate()
insert into t select 1999,getdate()
insert into t select 2000,getdate()
insert into t select 2001,getdate()
insert into t select 2900,getdate()

select
top 1 字段=A from T
where
A<=2000
order by A desc

select
字段=a.A
from
t a
where
a.A<=2000
and
not exists(select 1 from t where A<=2000 and A>a.A)

drop table T
lw1a2 2005-12-16
  • 打赏
  • 举报
回复
给出测试数据和结果
zoulipeng 2005-12-16
  • 打赏
  • 举报
回复
--以上没一个SQL是对的。。。。
yongwin 2005-12-16
  • 打赏
  • 举报
回复
如果就单单从,exists 与<=比的话,那一定是,exists效率高了,因为exists是对逻辑进行判断而<=是对每条记录的大小进行比较,效率当然就没有exists高了,楼主有兴趣的话可以看一下有关优化的文章,in,or,<=,>=,这些都是半优化的语句,而exists是全优化语句,还有楼主说的用exists怎么查询,对于楼主的这个问题如果用了,exists也不能提高多少效率因为,这个问题用exists写是这样的,select * from t a where not exists (select * from t where a.id=id and a>2000)这样写后可以说是用了,exists,可是它同时也用了子查询,而这同时也会影响查询的效率所以对于楼主这个问题,楼主用这两种办法都是差不多的
新鲜鱼排 2005-12-16
  • 打赏
  • 举报
回复
exists和in的效率基本相同,
我覺得中間過程太多也影響效率。
子陌红尘 2005-12-16
  • 打赏
  • 举报
回复
select
a.*
from
t a
where
a.A<=2000
and
not exists(select 1 from t where A<=2000 and A>a.A)
zoulipeng 2005-12-16
  • 打赏
  • 举报
回复
libin_ftsafe(子陌红尘|潇湘剑公子@dev-club)

两个SQL,我都执行了。结果都不对。:(
lw1a2 2005-12-16
  • 打赏
  • 举报
回复
楼主为什么要转换成有exists 语句的?

34,590

社区成员

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

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