积极答复者
哪种查询速度更快些呢?

问题
答案
-
使用in的慢
后面的查询可以改为:
select * from a inner join b on a.id = b.id
这个速度差别不大,sql server会自己优化的。
查询避免使用exists和in
in后面如果直接给值,如:in (1,2,3)还可能使用索引,如果是一个子查询,索引都用不到。
family as water- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09
-
两者的结果不同, 不应该直接比较
第二个语句实际执行的时候会是错的, 因为用 select *, a/b都有id, 字段名重复, 会报错.
抛开错误不管, 进一步分析, 第一个只返回a表结果, 第二个返回 a/b两个表的结果, 所以一般来说, 第二个的性能会差一些
再抛开返回的列不一样多的问题, 如果 a/b 是一对多, 或者多对多的关系, 那么第一个返回的结果集一般小于第二个, 理论上来说也是第二个的性能差一些.
如果上面那些差异都不管, 那么在查询优化器的作用下, 两者应该都差不多.
- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09
-
Just compare cost in execution plans.
- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09
全部回复
-
使用in的慢
后面的查询可以改为:
select * from a inner join b on a.id = b.id
这个速度差别不大,sql server会自己优化的。
查询避免使用exists和in
in后面如果直接给值,如:in (1,2,3)还可能使用索引,如果是一个子查询,索引都用不到。
family as water- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09
-
select * from (select *,row_number() over(order by id) tid from a where id in (select id from a inner join b on a.id = b.id where 1=1)) c where tid between 1 and 5
select * from (select *,row_number() over(order by id) tid from (select * from a inner join b on a.id = b.id where 1=1)) c where tid between 1 and 5这两种呢?在速度上,哪个快与慢?
-
两者的结果不同, 不应该直接比较
第二个语句实际执行的时候会是错的, 因为用 select *, a/b都有id, 字段名重复, 会报错.
抛开错误不管, 进一步分析, 第一个只返回a表结果, 第二个返回 a/b两个表的结果, 所以一般来说, 第二个的性能会差一些
再抛开返回的列不一样多的问题, 如果 a/b 是一对多, 或者多对多的关系, 那么第一个返回的结果集一般小于第二个, 理论上来说也是第二个的性能差一些.
如果上面那些差异都不管, 那么在查询优化器的作用下, 两者应该都差不多.
- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09
-
Just compare cost in execution plans.
- 已标记为答案 Nai-dong Jin - MSFTModerator 2010年6月17日 2:09