The query below runs extremely fast (Less than 1 second) with one ID
SELECT ID, GROUP_CONCAT(CODE SEPARATOR ' ')
FROM TABLE
WHERE TYPE='A' AND ID IN ( 1 )
GROUP BY ID;
But extremely slow (Over 10 seconds) when run with more than one ID
SELECT ID, GROUP_CONCAT(CODE SEPARATOR ' ')
FROM TABLE
WHERE TYPE='A' AND ID IN (1, 2)
GROUP BY ID;
I think it's because MySQL tries to perform the GROUP_CONCAT on all IDs first, then compares it with the IN constraint. Any ideas?
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `TABLE` ADD INDEX `table_idx_type_id` (`TYPE`,`ID`);
SELECT
TABLE.ID,
GROUP_CONCAT(TABLE.CODE SEPARATOR ' ')
FROM
TABLE
WHERE
TABLE.TYPE = 'A'
AND TABLE.ID IN (
1
)
GROUP BY
TABLE.ID
ORDER BY
NULL