2016-04-21 95 views
0

全部,SQLITE:優化ORDER BY查詢

我是iOS開發人員。目前我們已經在數據庫中存儲了2.5個缺乏數據。我們已經實現了搜索功能。以下是我們正在使用的查詢。

select CustomerMaster.CustomerName ,CustomerMaster.CustomerNumber, 
    CallActivityList.CallActivityID,CallActivityList.CustomerID,CallActivityList.UserID, 
    CallActivityList.ActivityType,CallActivityList.Objective,CallActivityList.Result, 
    CallActivityList.Comments,CallActivityList.CreatedDate,CallActivityList.UpdateDate, 
    CallActivityList.CallDate,CallActivityList.OrderID,CallActivityList.SalesPerson, 
    CallActivityList.GratisProduct,CallActivityList.CallActivityDeviceID, 
    CallActivityList.IsExported,CallActivityList.isDeleted,CallActivityList.TerritoryID, 
    CallActivityList.TerritoryName,CallActivityList.Hours,UserMaster.UserName, 
    (FirstName ||' '||LastName) as UserNameFull,UserMaster.TerritoryID as UserTerritory 
from 
    CallActivityList 
    inner join CustomerMaster 
     ON CustomerMaster.DeviceCustomerID = CallActivityList.CustomerID 
    inner Join UserMaster 
     On UserMaster.UserID = CallActivityList.UserID 
where 
    (CustomerMaster.CustomerName like '%T%' or 
    CustomerMaster.CustomerNumber like '%T%' or 
    CallActivityList.ActivityType like '%T%' or 
    CallActivityList.TerritoryName like '%T%' or 
    CallActivityList.SalesPerson like '%T%' ) 
    and CallActivityList.IsExported!='2' and CallActivityList.isDeleted != '1' 
order by 
    CustomerMaster.CustomerName 
limit 50 offset 0 

不使用'order by'查詢返回0.5秒結果。但是當我附上'order by'時,時間會增加到2秒。

我試過編制索引,但沒有做出任何明顯的改變。任何人請幫助。如果我們沒有通過查詢,那麼我們怎麼快速做到這一點。

在此先感謝。

回答

1

這是由於限制。如果沒有ORDER BY,只需要處理50條記錄,並且將返回50條記錄。使用ORDER BY必須處理所有記錄以確定哪些記錄是前50(按順序)。

問題是ORDER BY是在一個連接的表上執行的。另外,你可以在主表上應用限制(我認爲它是CallActivityList),然後加入。

SELECT ... 
FROM 
    (SELECT ... FROM CallActivityList ORDER BY ... LIMIT 50 OFFSET 0) AS CAL 
    INNER JOIN CustomerMaster ON ... 
    INNER JOIN UserMaster ON ... 
    ORDER BY ... 

這會降低加入表格的成本。如果這是不可能的,至少嘗試加入CallActivityListCustomerMaster。適用於這些限制,最後加入UserMaster

SELECT ... 
FROM 
    (SELECT ... 
    FROM 
     CallActivityList 
     INNER JOIN CustomerMaster ON ... 
    ORDER BY CustomerMaster.CustomerName 
    LIMIT 50 OFFSET 0) AS ActCust 
    INNER JOIN UserMaster ON ... 
ORDER BY ... 

此外,爲了使排序明確,我會包括更多的列順序,如通話日期和通話ID。否則,這可能導致不一致的分頁。

+0

我知道,如果你可以幫我優化這個查詢'訂單'。 – Nikh1414