有個存儲過程,功能是:根據用戶名查詢非好友的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作為參數傳遞到存儲過程中,在程序外面查詢好友,但要改動程序。













后來用了臨時表的方案,如下:

















問題較好的解決了,因為臨時表temp中保存的都是好友的ID,非常快,不用每次都去執行好友的篩選邏輯。另外一種方式是:將好友ID作為參數傳遞到存儲過程中,在程序外面查詢好友,但要改動程序。