select cu.flowers,
(select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank,
cu.UserID,
cu.UserBBName,
cu.UserPhoto,
cu.UserVotes,
gender=case cmi.gender when 1 then '男' else '女' end,
Convert(varchar(20),datediff(Month,Birthday,getdate())/12) +'岁'+ Convert(varchar(20),datediff(Month,Birthday,getdate())%12) + '个月' as age
from CM_Users_Tbl cu inner join CM_UserInfo_Tbl cmi on cmi.userid=cu.userid
order by cu.UserVotes desc
然后我把那两列的计算项去掉,换成在C#中处理,也是要14秒。
SQL code
select cu.flowers,
(select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank,
cu.UserID,
cu.UserBBName,
cu.UserPhoto,
cu.UserVotes,
cmi.gender
Birthday
from CM_Users_Tbl cu inner join CM_UserInfo_Tbl cmi on cmi.userid=cu.userid
order by cu.UserVotes desc
不知道瓶颈在哪里,希望各位大侠帮忙下。
------解决方案-------------------- (select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank,
这快应该是慢的原因,会做很多全表扫描 你ctrl + L 查看一下执行计划就知道了
------解决方案-------------------- select cu.flowers, (select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank, cu.UserID, cu.UserBBName, cu.UserPhoto, cu.UserVotes, gender=case cmi.gender when 1 then '男' else '女' end, Convert(varchar(20),datediff(Month,Birthday,getdate())/12) +'岁'+ Convert(varchar(20),datediff(Month,Birthday,getdate())%12) + '个月' as age from CM_Users_Tbl cu inner join CM_UserInfo_Tbl cmi on cmi.userid=cu.userid order by cu.UserVotes desc
------解决方案--------------------
SQL code
建议 在uservotes 和 userid 字段上创建索引。
或者 创建一个包含索引 比如
create index idx_name on CM_Users_Tbl (uservotes desc,userid desc)
include (flowers,UserBBName,UserPhoto)
------解决方案--------------------
------解决方案-------------------- (select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank, count(b.userid)+1 us 这个中间怎么有个us,啥意思?不懂
------解决方案-------------------- 子查询(select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank, 是慢的主要原因
------解决方案-------------------- 你这索引假脱机 耗费了45%。 可以试一试 清理缓存,再试一试。
------解决方案-------------------- 1. CM_UserInfo_Tbl CM_Users_Tbl 两个表分别有多大数据量? 2.(select count(b.userid)+1 us from cm_users_tbl b WHERE CU.uservotes<b.uservotes ) as rank 这个如果只是用来做排序,用row_number() 来实现比较合适
------解决方案-------------------- cu.UserPhoto, 是否图片?