需要MySQL查询优化

时间:2011-11-02 20:50:19

标签: mysql optimization

我的查询速度很慢。我知道使用依赖子查询是不好的,但我想不出另一种方法来获取我想要的数据。

基本上,我想标记过去6个月内至少有50张发票的客户,但本月没有发票。

这就是我目前的情况:

select
    Customer.name,
    Customer.id,
    Customer.latitude,
    Customer.longitude
from
    Customer
where
    EXISTS (
        SELECT 
            *
        FROM
            Invoice_Header
        WHERE
            Invoice_Header.inv_date BETWEEN '2011-03-02' AND '2011-10-02'
        AND
            Invoice_Header.account_number = Customer.account_number
        HAVING COUNT(invoice_num) > 50
    )
    AND NOT EXISTS (
        SELECT * 
        FROM 
            Invoice_Header 
        WHERE
            InvHead.inv_date > '2011-10-02'
        AND
            InvHead.account_number = Customer.account_number
    )
Group by name;

客户表约有12k记录,Invoice_Header约有2,500条记录。

我在inv_date,account_number(两个表中)都有索引。

对于如何提高速度的任何建议都将不胜感激。

4 个答案:

答案 0 :(得分:3)

这应该消除相关的子查询并且明显更快:

SELECT c.name, c.id, c.latitude, c.longitude
FROM Customer c
INNER JOIN (
  SELECT account_number
  FROM Invoice_Header ih
  WHERE ih.inv_date BETWEEN '2011-03-02' AND '2011-10-02'
  GROUP BY account_number
  HAVING COUNT(*) > 50
  MINUS
  SELECT DISTINCT account_number
  FROM Invoice_Header ih
  WHERE ih.inv_date > '2011-10-02'
) tbl
ON tbl.account_number = c.account_number

答案 1 :(得分:2)

select
    C.name,
    C.id,
    C.latitude,
    C.longitude,
    I.account_number,         
    count( IF(I.inv_date>='2011-03-02' AND I.inv_date <='2011-10-02',I.inv_date,NULL )) as inv_count_6,
    count( IF(I.inv_date > '2011-10-02',I.inv_date,NULL )) as inv_count_1

from Customer C
LEFT JOIN Invoice_Header I
ON C.account_number = I.account_number 

GROUP BY C.id, I.account_number
HAVING inv_count_6 >= 50 AND inv_count_1=0
WHERE I.inv_date  BETWEEN '2011-03-02' AND '2011-10-02'

注意:

1.发票至少为50.所以条件是> = 50不是> 50。

2.您必须将索引添加到列inv_date

答案 2 :(得分:2)

我建议:

SELECT
    c.name,
    c.id,
    c.latitude,
    c.longitude
FROM
    Customer AS c
    INNER JOIN (
        SELECT account_number, count(*) AS invoice_count
        FROM Invoice_Header
        WHERE inv_date >= '2011-03-02' AND inv_date <= '2011-10-02'
        GROUP BY account_number
    ) AS lsm
        ON c.account_number = lsm.account_number
    LEFT JOIN (
        SELECT account_number, count(*) AS invoice_count
        FROM Invoice_Header
        WHERE inv_date > '2011-10-02'
        GROUP BY account_number
    ) AS lm
        ON c.account_number = lm.account_number
    WHERE
        lsm.invoice_count >= 50
        AND IFNULL(lm.invoice_count, 0) = 0

答案 3 :(得分:1)

尝试使用explain运行查询,并查看是否需要其他索引。