SQL查询语句优化的一点

来源:互联网 发布:Linux deploy vnc 编辑:程序博客网 时间:2024/05/22 04:48
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

(1)INSERT[INTO]BSELECT id,field1,field2 FROMAWHERENOTEXISTS(SELECT idFROMBWHEREid=[A.]id) 

(2)INSERT[INTO]BSELECT*FROMAWHEREidNOTIN(SELECTidFROMB)

---------------------------------------------------------------------------

这两句,都是将A表中存在,但B表中不存在的数据,插入到B表中,关联比较字段为id.
但这两句的执行效率,却是有数量级的差别.

结论有两点:
尽量用EXISTS和NOTEXISTS代替IN和NOTIN不要偷懒,尽量不用SELECT*FROM....,而要写字段名SELECTfield1,field2,.... 
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>