2012-07-25 82 views
0

我有這個疑問,其正在約40-50秒加載我如何優化這個花費很多時間的查詢?

SELECT 
    members.latitude, 
    members.longitude, 
    members.mem_id 
FROM members 
WHERE profile_type != "C" 
    AND (gender = 'm' 
      OR gender = 'f') 
    AND members.mem_id IN(SELECT DISTINCT 
          n2.mem_id 
          FROM network n1, 
          network n2 
          WHERE n1.frd_id = n2.mem_id 
           AND n1.mem_id = '48' 
           AND n2.frd_id = '48') 
ORDER BY profilenam 

有其中包含的用戶朋友們

請幫網表..

+0

添加索引到你的表 – 2012-07-25 11:20:02

+0

目前已經有指數在這兩個表 – user1551419 2012-07-25 11:20:44

+0

@ user1551419'AND(性別添加項= 'm' 或性別='f')'這部分似乎是額外的(除非有另一種可能性)。 – Leri 2012-07-25 11:22:41

回答

3

這是因爲子的慢-query二手嘗試沒有子查詢中使用派生表:

SELECT latitude, longitude, a.mem_id 
FROM members a 
    INNER JOIN (SELECT DISTINCT n2.mem_id AS mem_id 
       FROM network n1, 
         network n2 
       WHERE n1.frd_id = n2.mem_id 
         AND n1.mem_id = '48' 
         AND n2.frd_id = '48' 
       ) b 
       ON a.mem_id = b.mem_id 
WHERE profile_type != "C" 
     AND (gender = 'm' 
      OR gender = 'f') 
ORDER BY profilenam; 

上表中還添加適當的索引和使用EXPLAIN EXTENDED檢查索引用法:

ALTER TABLE network ADD KEY ix1(mem_id); 
ALTER TABLE network ADD KEY ix1(frd_id); 
+0

,謝謝@omesh – user1551419 2012-07-25 12:01:31

0

IN子句只適用於結果集小的情況。對於較大的結果集,請考慮重寫查詢。過濾器(IN子句產生的)是一種昂貴的數據庫操作。

0

用EXISTS替換IN子句。

只有1000允許在收集

(items_num = 1000)