网络服务器软件开发/中间件开发,关注ACE/ICE/boost

C++博客 首页 新随笔 联系 聚合 管理
  152 Posts :: 3 Stories :: 172 Comments :: 0 Trackbacks
      有个存储过程,功能是:根据用户名查询非好友的ID,代码如下:
begin

  select UserID  from  Users
    where
    UserID 
!= pUserID and
    Users.UserID  not 
in
    (
        select FriendID from Users_Friend where Users_Friend.UserID 
= pUserID and DeleteFlag = 0
    )
    and
    Users.Name like BINARY  concat(
'%',pUserName,'%')  ;

end
 其中,pUserID是搜索者的UID,pUserName是要搜索的用户名。今天发现这个存储过程非常慢,分析结论是:not in 后面的select子查询是每次都执行的,这出乎意料!mysql难道不能优化掉这样的查询吗?
      后来用了临时表的方案,如下:
begin

    Create TEMPORARY  Table  IF NOT EXISTS temp(FriendID 
int );
    insert into temp(FriendID) select FriendID from Users_Friend where Users_Friend.UserID 
= pUserID and DeleteFlag = 0;

      select UserID  from  Users
    where
    UserID 
!= pUserID and
    Users.UserID  not 
in
    (
        select FriendID from temp
    )
    and
    Users.Name like BINARY  concat(
'%',pUserName,'%')  ;

    drop TEMPORARY  table temp;
end

问题较好的解决了,因为临时表temp中保存的都是好友的ID,非常快,不用每次都去执行好友的筛选逻辑。另外一种方式是:将好友ID作为参数传递到存储过程中,在程序外面查询好友,但要改动程序。
 
posted on 2011-01-13 13:05 true 阅读(2920) 评论(0)  编辑 收藏 引用 所属分类: mysql

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理