需求如下:
表table1(phone)
表table2(phone,style1,style2,indatetime)
用一条select语句关联查询出table1中的Style1='a'的phone数量、Style1='a'且Style2='b'的phone数量、每个style1='a'的phone最大的indatetime。我原来是这样写的:
select a.phone,b.num1,c.num2,b.indatetime from table1 a 
left join (select count(phone) as num1,phone,max(indatetime) as indatetime from table2 where Style1='a' group by phone) b on a.phone=b.phone
left join (select count(phone) as num2,phone from table2 where style1='a' and style2='b' group by phone) c on a.phone=c.phone
现在问题出在:table1和table2在不同的服务器上,我这样通过两个左连接table2速度很慢(实际要7-8秒),每次都超时(程序允许的查询时间是3秒)。请问大家还有没有更好更快的写法? 

解决方案 »

  1.   

    (select count(phone) as num1,phone,max(indatetime) as indatetime from table2 where Style1='a' group by phone) b改为表变量存储或用临时表。你的子查询查另台机器的表,字段又是字符型的,肯定慢。
    先预处理数据,再得到结果,不要一口气吃完
      

  2.   

    从当前服务器打开另一台服务器可用下面语句,这就好象在同一台服务器上操作一样方便了OPENDATASOURCE ('SQLOLEDB', 
                   'Data Source=服务器a;User ID=用户名;Password=密码' ).数据库.dbo.表名
      

  3.   

    hejiahuanle() 的OPENDATASOURCE方法拭了下,速度更慢了;另外目标服务器已经链接上了,但链接服务器里没有我要的表,能否添加(我找不到该功能).