2016-11-16 112 views
2

我有一個系統,其中商店是一個帳戶,顧客在這些商店購物。有一張表可以存儲多對多的客戶和商店的關聯。該表的關鍵屬性是accountid,customerid和last_visit_date。對於一系列accountids,我需要找到每個客戶的最近訪問。我有一個完美的查詢,但似乎是效率低下,因爲它用完了大約21000個客戶的內存。MySQL查詢內存不足

SELECT ac.customerId FROM account_customer ac 
     INNER JOIN (SELECT customerId, max(last_visit_date) AS 
        LastVisitDate FROM account_customer 
        WHERE accountId in   
        (311,307,318,320,321,322,323,332,347,439,519,630,634,643) 
       GROUP BY customerId) grouped_ac 
    ON ac.customerId = grouped_ac.customerId 
      AND ac.last_visit_date = grouped_ac.LastVisitDate 
      AND ac.last_visit_date <= '2016-10-18' 
      OR ac.last_visit_date is null 

當我運行上面的查詢,它給了我一個較小的數據集正確的結果,但對於更大的數據集,我得到的內存錯誤。我甚至沒有談論過一個非常大的集合 - 大約有2萬多個客戶。

任何幫助,將不勝感激。

+1

發佈您的PHP代碼。 –

+3

在MySQL中爲查詢運行'EXPLAIN'計劃。它可能暗示缺少索引。 – bcmcfc

+0

現在我只是試圖運行原始查詢,我直接在mysql服務器上使用mysql workbench發佈內存並且內存不足。 –

回答

1

你可能意味着

ac.customerId = grouped_ac.customerId 
AND ac.last_visit_date = grouped_ac.LastVisitDate 
and (ac.last_visit_date <= '2016-10-18' or ac.last_visit_date is null) 

我認爲,如果沒有括號,查詢可有返回的所有記錄LAST_VISIT_DATE爲空。

看看How exactly does using OR in a MySQL statement differ with/without parentheses?的答案。

+0

你說得對。這就是發生了什麼事。謝謝。 –

+0

這是否導致內存問題,因爲這麼多記錄回來了? – CGritton

+0

我這麼認爲。一旦我把這些括號放在一起 - 它沒有任何內存耗盡就可以正常工作。 –