2017-06-01 38 views
0

我們獲得的結果是正確的,但它需要太多的時間來執行。我們可以優化查詢,這將花費更少的時間來執行。如何使用內部連接和子查詢優化SQL查詢和返回計數

SELECT c.client_id 
FROM client_master c 
INNER JOIN user_visit_record u ON u.client_id = c.client_id 
WHERE c.dept_id ='1' 
    AND c.branch_id='1' 
    AND c.client_status IN('Hot','Warm','Cold','Quotation') 
    AND u.next_followup_date < '2017-06-01' 
    AND u.visit_id IN 
    (SELECT max(visit_id) 
    FROM user_visit_record 
    WHERE client_id=c.client_id) 

在此先感謝。

+1

檢查visit_id字段和client_id的索引。 –

+0

我們沒有使用索引 – Vijaya

+0

如果您爲相關列創建索引,可能會獲得更多速度。 –

回答

0

我已經使用*查詢,你能做的就是隻選擇需要的列,單程優化

和MySQL有一些現有的解決方案,檢查此Article

SELECT c.client_id 
    FROM 
     (SELECT * 
     FROM client_master 
     WHERE dept_id ='1' 
       AND branch_id='1' 
       AND IN('Hot','Warm','Cold','Quotation')) AS c 
    INNER JOIN 
     (SELECT * 
     FROM user_visit_record 
     WHERE next_followup_date < '2017-06-01' 
       AND visit_id IN 
      (SELECT max(visit_id) 
      FROM user_visit_record 
      WHERE client_id=c.client_id)) AS u 
      ON u.client_id = c.client_id 
1

這裏是優化查詢:

SELECT c.client_id 
FROM client_master c 
JOIN (SELECT * FROM user_visit_record u ORDER BY u.visit_id DESC) AS t ON t.client_id = c.client_id 
WHERE c.dept_id ='1' 
AND c.branch_id='1' 
AND c.client_status IN('Hot','Warm','Cold','Quotation') 
AND t.next_followup_date < '2017-06-01' 
GROUP BY t.clientid 
+0

謝謝你@Kruti Patel ..但這個查詢檢索錯誤的結果。 – Vijaya

+0

我們能否爲此獲得另一種解決方案? – Vijaya

0

試試這個:

SELECT client_id FROM 
    (
    SELECT client_id 
     FROM client_master 
     WHERE dept_id ='1' AND branch_id='1' AND client_status IN('Hot','Warm','Cold','Quotation') 
) AS c 

    NATURAL JOIN 

    (
    SELECT client_id 
     FROM user_visit_record 
     INNER JOIN (
      SELECT client_id, max(visit_id) as max_visit 
      FROM user_visit_record 
       GROUP BY client_id 
     ) AS max_user_visit 
      ON (user_visit_record.client_id = max_user_visit.client_id) 
       AND (user_visit_record.visit_id = max_visit) 
     WHERE next_followup_date < '2017-06-01' 
) AS u