日期:2014-05-18  浏览次数:20411 次

高分求救在大约20万条记录下如何在有 or 的情况下实现高速度查询
有个例子,需要从大约10-50个城市下查询符合条件的记录,城市用的是 city字段, 这样我的语句大致是:
select name,age from Users where city='beijing' or city='shanghai' or city='guangzou' ......
如果在1个城市下查询速度很快,但是在50个城市里面查询符合条件的记录速度会非常慢,我已经给city加索引了,但是速度仍然很慢,我也试过用in 来代替or,但是速度依然很慢,请问各位是否有什么办法可以提高查询速度,比如需要在50个城市查询的情况下, 我的语句要如何修改呢??? 谢谢


------解决方案--------------------
1、给city加索引
2、使用in(....) 或 or来查询。

既然这两条件都有了,还是慢?
不过20W不是很大,个人觉得是否还有其他问题。
------解决方案--------------------
如是你要查找50多个城市的话,不如用not in ()
------解决方案--------------------
ROW_NUMBER() ?
楼主用的Oracle还是SQL2005?

in是一个问题,另一个问题是 order by 后面的 case when
------解决方案--------------------
用临时表把你那些城市存起来
------解决方案--------------------
看LZ的语句索引是用不上了,这样的条件7秒也算正常的
------解决方案--------------------
SQL code
--try
create table #Cities(CityName nvarchar(16) primary key)
declare @sql nvarchar(4000), @cities nvarchar(512)
set @cities = 'BL0,BL1,BL2,BL3,BL4,BL8,BL9,M1,M11,M12,M13,M14,M15,M16,M17,M18,M19,M2,M20,M21,M22,M23,M24,M25,M26,M27,M28,M29,M3,M30,M31,M32,M33,M34,M35,M38,M4,M40,M41,M43,M44,M45,M46,M5,M6,M60,M8,M9,M90,OL1,OL10,OL11,OL12,OL16,OL2,OL4,OL5,OL6,OL7,OL8,OL9,SK1,SK14,SK15,SK16,SK2,SK3,SK4,SK5,SK8,WA14,WA15,'
set @sql = 'insert #Cities select ''' + left(@cities,charindex(',',@cities)-1) + ''' '
set @cities = stuff(@cities,1,charindex(',',@cities),'')
while @cities<>''
begin
    set @sql = @sql + ' union all select ''' + left(@cities,charindex(',',@cities)-1) + ''' '
    set @cities = stuff(@cities,1,charindex(',',@cities),'')
end
--print @sql
exec(@sql)

Select top 200  ROW_NUMBER() Over(Order By CompanyID ) AS ROWNUM,cat.categoryid ,Company, CompanyID, Keyword , FullAddress,cat.CategoryName  
FROM Ask_Companies inner join Ask_Category cat on cat.categoryid=ask_companies.categoryid
join #Cities on LEFT([Business Postal Code],CHARINDEX(' ', [Business Postal Code])-1)=#Cities.CityName 
Where (1=1) and (cat.categoryname= 'Abattoirs' or dbo.Ask_FN_GetCategoryName(Ask_Companies.categoryid2)= 'Abattoirs' 
    or dbo.Ask_FN_GetCategoryName(Ask_Companies.categoryid3)= 'Abattoirs ')   
Order By case when Charindex( 'Company',Keyword) >0 then 0 else 1 end  

drop table #Cities

------解决方案--------------------
select name,age from Users where city= 'beijing ' 
union all
 select name,age from Users where city= 'shanghai ' 
union all
select name,age from Users where city= 'guangzou '
------解决方案--------------------
可以根据你的城市分成几个表(你现在可以临时表)
如:以ABC字母开头的一个表
以DEF字母开头的一个表
.
.


查询的时候用动态表的形式查


这个只是我一个想法而已,不知道对不对