GROUP_CONCAT distinct和sub_query的性能问题

时间:2014-12-23 03:01:30

标签: mysql performance join distinct group-concat

我正在尝试在MYSQL DB中执行此查询。

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

我尝试添加INDEX,但仍然没有运气。(只有这些子查询需要大约30-40秒才能执行)

我尝试实现了Joins,但因为我是mysql的新手,所以没有运气..

任何人都可以帮助我更快地执行查询吗?

2 个答案:

答案 0 :(得分:0)

该子查询的最佳索引是EMP_DEPT(EMPT_ID, EmpDept)。那是你定义的索引吗?

第二个group_concat()无法利用索引。

如果删除这两行,查询的速度会快多少?

答案 1 :(得分: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上有索引。