如何使用内部联接和子查询优化SQL查询和返回计数

时间:2017-06-01 07:57:59

标签: mysql

我们正在获得正确的结果但是它花费了太多时间来执行。我们可以优化查询,这将花费更少的时间来执行。

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)

提前致谢。

3 个答案:

答案 0 :(得分:1)

以下是优化查询:

<<

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

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