SQLITE:优化ORDER BY查询

时间:2016-04-21 15:15:26

标签: iphone sqlite search sql-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 个答案:

答案 0 :(得分: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 ...

这将降低加入表格的成本。如果无法做到这一点,请至少尝试将CallActivityList加入CustomerMaster。将限制应用于这些限制,最后加入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。否则,这可能会导致分页不一致。