怎么优化如下子查询语句:
select * from tb_a a where a.id in (select b.id from tb_b b where b.id <1000)
回答:这是典型的子查询语句,所谓子查询就是指在in() ,exists()中的select,在from之后的select称为动态视图。
子查询的优化有这么几种方法:
(1)in子查询可以优化成关联子查询:
select * from tb_a a where a.id in (select b.id from tb_b b where a.id=b.id and b.id <1000)
——这个优化的提升是最明显的
(2)更进一步,优化成exists关联子查询
select * from tb_a a where exists (select 1 from tb_b b where a.id=b.id and b.id <1000)
——exists和in的不同是,in需要判断出所有的记录,exists只需要判断出存在记录
(3)去掉子查询用表连接
select * from tb_a a,tb_b b where a.id=b.id and b.id <1000
——这种方法对于 not in ,not exists就不可转换
select * from tb_a a where a.id in (select b.id from tb_b b where b.id <1000)
回答:这是典型的子查询语句,所谓子查询就是指在in() ,exists()中的select,在from之后的select称为动态视图。
子查询的优化有这么几种方法:
(1)in子查询可以优化成关联子查询:
select * from tb_a a where a.id in (select b.id from tb_b b where a.id=b.id and b.id <1000)
——这个优化的提升是最明显的
(2)更进一步,优化成exists关联子查询
select * from tb_a a where exists (select 1 from tb_b b where a.id=b.id and b.id <1000)
——exists和in的不同是,in需要判断出所有的记录,exists只需要判断出存在记录
(3)去掉子查询用表连接
select * from tb_a a,tb_b b where a.id=b.id and b.id <1000
——这种方法对于 not in ,not exists就不可转换
上述三种优化,理论上讲(3)最快,其次是(2)高校,而(1)是低效!
出自:http://www.tsingsong.com/jforum/posts/list/202.page