现有两个表:
Phone表(字段Phone为11位手机号码)。
Area表(字段Phone1手机号码头7位起始数, Phone2手机号码头7位中止数, Area为所属区域)。现将手机号码及其所对应的所属区域存于另一表PhoneArea中,请在sql server中用最优的算法加以实现。例:Phone表中有一手机号码Phone(13812345678)。
    Area表中有一纪录为Phone1(1381230), Phone2(1381239), Area(北京)处理后的纪录在新表PhoneArea中为Phone(13812345678), Area(北京)
我原写的sql语句为: Select a.Phone, b.Area Into PhoneArea From Phone As a, Area as b Where substring(a.Phone, 1, 7) >= b.Phone1 And substring(a.Phone, 1, 7) <= b.Phone2此语句执行了二三十分钟也没执行玩,所以我就让他停止了(每个表中的纪录至少2万条以上。)。请问哪位高手有更优的办法能让他在一分钟之内处理完呢?

解决方案 »

  1.   

    如果这三个字段都是字符型的
    Select a.Phone, b.Area Into PhoneArea From 
    Phone As a, Area as b Where a.Phone between
    b.Phone1 And  b.Phone2;给这三个字段创建索引
      

  2.   

    问题在这里解决了
    http://expert.csdn.net/Expert/topic/2410/2410594.xml?temp=.1596491
      

  3.   

    但我试了试:首先是将Phone表中的纪录处理为7位,类型bigint。
    然后将Area中的Phone1,Phone2转换为bigint,这样就是同等类型。re: 你同等类型就不存在转换的问题当然快了。之后如此:Select a.Area, p.Phone
    From Area as a, Phone as p
    Where p.Phone Between a.Phone1 And Phone2这样仅运行了几秒钟。但若将Phone1 和 Phone2 都乘10000(将号段转为11位,bigint)。Phone中的字段仍为原来的11位(bigint),这样就运行好多分钟(我没让他运行完)。re: 这又回到开始时你的问题上:Phone1 和 Phone2 都乘10000 你在select 时再乘的话,弊端在:没有用到表的索引,索引用不上! 你有10000条记录就好乘 200000次。你要:
    ALTER TABLEArea ADD Phone1_temp as Phone1*1000
    ALTER TABLEArea ADD Phone2_temp as Phone2*1000CREATE INDEX TABLEArea_Phone1_temp_index  ON TABLEArea(Phone1_temp)
    CREATE INDEX TABLEArea_Phone2_temp_index  ON TABLEArea(Phone2_temp)