2014-12-23 42 views
0

我想在MYSQL數據庫中執行此查詢。GROUP_CONCAT與獨特和子查詢性能問題

SELECT FirstName,LastName 
    CONCAT(COALESCE(Address1, ''), 
    COALESCE(Address2, '')) AS Address2, 
    (SELECT GROUP_CONCAT(EmpDept ' ') FROM EMP_DEPT 
    USE INDEX (EMP_DEPT_IDX) 
    WHERE EMP_DEPT.EMP_ID = EMP.EMP_ID) AS DEPT, 
    COUNT(PIN) AS PIN, 
    MIN(SALARY) AS SALARY, 
    GROUP_CONCAT(DISTINCT PAY_CODE SEPARATOR ' ') AS PAYROLL_CODE 
FROM EMP WHERE HOUSE='YELLOW' AND HOUSE_AREA='220' 
    AND (JOIN_YEAR = '2011' OR JOIN_YEAR = '2012') 
    AND EMP_BAND='G' 
    AND (FRESHER = 'N' OR FRESHER = 'FALSE') 
    AND PIN IS NOT NULL 
    AND SALARY > 0 
GROUP BY FirstName,LastName Address3, Address2, DEPT 

該查詢工作正常,我得到所需的結果集。

只有問題,沒有對這兩行代碼巨大的性能損失,採用GROUP_CONCAT寫,

(SELECT GROUP_CONCAT(EmpDept ' ') FROM EMP_DEPT 
    USE INDEX (EMP_DEPT_IDX) 
    WHERE EMP_DEPT.EMP_ID = EMP.EMP_ID) AS DEPT 


GROUP_CONCAT(DISTINCT PAY_CODE SEPARATOR ' ') AS PAYROLL_CODE 

我嘗試添加索引,但仍然沒有運氣。(僅這些子查詢正在各地30-40sec執行)

我試圖實現連接,但我是新來的mysql沒有運氣..

誰能幫助我在做我的查詢執行得更快?

回答

0

嘗試與子查詢外部聯接替換相關子查詢:

SELECT FirstName,LastName 
    CONCAT(COALESCE(Address1, ''), 
    COALESCE(Address2, '')) AS Address2, 
    COALESCE(DEPT, '') AS DEPT, 
    COUNT(PIN) AS PIN, 
    MIN(SALARY) AS SALARY, 
    GROUP_CONCAT(DISTINCT PAY_CODE SEPARATOR ' ') AS PAYROLL_CODE 
FROM EMP 
LEFT JOIN (SELECT EMP_ID, GROUP_CONCAT(EmpDept SEPARATOR ' ') AS DEPT 
      FROM EMP_DEPT 
      GROUP BY EMP_ID) AS EMP_DEPT ON EMP_DEPT.EMP_ID = EMP.EMP_ID 
WHERE HOUSE='YELLOW' AND HOUSE_AREA='220' 
    AND (JOIN_YEAR = '2011' OR JOIN_YEAR = '2012') 
    AND EMP_BAND='G' 
    AND (FRESHER = 'N' OR FRESHER = 'FALSE') 
    AND PIN IS NOT NULL 
    AND SALARY > 0 
GROUP BY EMP.EMP_ID 

另外,我改變了最終GROUP BY使用EMP_ID列,而不是返回的列值。

也可能只是更改最後的GROUP BY將解決您的問題。按索引列分組應該更高效,因此請確保您有EMP_ID的索引。

0

該子查詢的最佳索引是EMP_DEPT(EMPT_ID, EmpDept)。那是你定義的索引嗎?第二個group_concat()不能利用索引。

如果刪除這兩行,查詢速度會快多少?