where 条件并不是越多越好
今天在写一个sql时,遇到这么个问题,where条件多写了几个,结果结果执行计划显得很槽糕:
表A 有字段 heard_id,class_no,bath_no,class_name
表B有字段 heard_id,class_no,bath_no,class_value
首先A表与B表是通过heard_id相关联,首先得承认这2个表设计有点问题,不满足范式的要求,有冗余的信息,如class_no,bath_no,结果我在写写sql时写成这个样子:
select a.class_no,a.batch_no,a.class_name,b,class_value
from a,b
where a.heard_id = b.heard_id
and a.class_no = b.class_no
and a.batch_no = b. batch_no
and a.class_no = 10;
结果执行计划显示,A表在关联B表的时候,并没有用heard_id这个字段的索引,而是选择用了class_no,batch_no的联合索引,结果导致这个sql跑了N久没跑出来,后来稍微改了下,把class_no,batch_no条件拿掉了,变成
select a.class_no,a.batch_no,a.class_name,b,class_value
from a,b
where a.heard_id = b.heard_id
and a.class_no = 10;
这样写执行计划就选择了 heard_id这个字段的索引,很快就查询出来了,其实2个表关联通过heard_id就足够了,这也许是很多开发人员的开发习惯,只要可以,就把已知的所有条件都写在where字句中,以确保万无一失,其实有时候这样做会适得其反,大家要注意了。。。。。。