mysql查询优化vs内连接

时间:2014-10-14 13:24:07

标签: mysql group-by where-clause

我的查询需要永远。

我无法找到让它更快的方法。 我在互联网上寻找优化技巧,但没有找到任何可以加快速度的方法。

也许,新鲜的眼睛看到我没有做过的事情:)

以下是查询:

Select *,  sum(collection) as tot

 from
(
    SELECT  PHYS.PHYS_ID,
        month(PMT.DT_PD) as Month,
        year(PMT.DT_PD) as Year,
        PRAC.LOC_ID,
        sum(ABS(PMT.PMT_AMT)) as collection         

    FROM
        IDR_ENC ENC,
        IDR_PHYS_PT_XREF PHY_PT,
        IDR_PRACT_LOC PRAC,
        IDR_PMT PMT,
        IDR_PHYS PHYS,
        IDR_CHGS CHG

    where
        ENC.PT_ID      = PHY_PT.PT_ID AND
        ENC.ENC_LOC    = PRAC.LOC_ID  AND
        PHY_PT.PHYS_ID = PHYS.PHYS_ID AND
        PHY_PT.PT_ID   = CHG.PT_ID    AND   
        PMT.CHG_ID     = CHG.CHG_ID   AND              
        DATE_FORMAT(PMT.DT_PD, '%Y-%m-%d') >= '2014-01-01' and 
        DATE_FORMAT(PMT.DT_PD, '%Y-%m-%d') <= '2014-03-31'  and
        PRAC.LOC_ID IN (SELECT LOC_ID FROM IDR_PRACT_LOC WHERE LOC_ID != 0) AND
        PHYS.PHYS_ID in (SELECT PHYS_ID FROM IDR_PHYS WHERE PHYS_ID != 0) AND
        PMT.TRN_TYP NOT IN ('A', 'B', 'R', 'T') AND
        CHG.CPT4_CD NOT LIKE 'J%'

    GROUP BY PHYS.PHYS_ID,  month(PMT.DT_PD),year(PMT.DT_PD) 

)TOT_COLL 

group by month,year

1 个答案:

答案 0 :(得分:1)

  1. 内部查询中的GROUP BY不包含PRAC.LOC_ID
  2. 如果是整个查询,那么您可以在内部查询中获得所需的结果
  3. 您经常调用date_format“,最好将”2014-01-01“和”2014-03-31“转换为日期(此列上的+索引,如果有的话,可以使用)
  4. PHYSESSPHID_ID in(SELECT PHYS_ID FROM IDR_PHYS WHERE PHYS_ID!= 0)必须替换为PHYS.PHYS_ID!= 0
  5. PRAC.LOC_ID IN(SELECT LOC_ID FROM IDR_PRACT_LOC WHERE LOC_ID!= 0)必须替换为PRAC.LOC_ID!= 0