У меня есть запрос с несколькими подзапросами, чтобы подсчитать, сколько пользователей, вовлеченных в определенную транзакцию, зависит от статуса.
SELECT * FROM (
SELECT
DATE(changes.created_at) AS `date`,
SUM(IF(changes.status = 15, 1, 0)) AS installed_daily,
SUM(IF(changes.status = 3, 1, 0)) AS port_reserved,
(
SELECT COUNT(DISTINCT created_by) FROM applicant_state_changes
WHERE DATE(created_at) = DATE(changes.created_at) AND status = 3
) AS user_port_reserved,
SUM(IF(changes.status = 5, 1, 0)) AS document_validated,
(
SELECT COUNT(DISTINCT created_by) FROM applicant_state_changes
WHERE DATE(created_at) = DATE(changes.created_at) AND status = 5
) AS user_document_validated,
SUM(IF(changes.status = 7, 1, 0)) AS account_created,
(
SELECT COUNT(DISTINCT created_by) FROM applicant_state_changes
WHERE DATE(created_at) = DATE(changes.created_at) AND status = 7
) AS user_account_created,
SUM(IF(changes.status = 11, 1, 0)) AS jo_created,
(
SELECT COUNT(DISTINCT created_by) FROM applicant_state_changes
WHERE DATE(created_at) = DATE(changes.created_at) AND status = 11
) AS user_jo_created
FROM applicant_state_changes AS changes
GROUP BY DATE(changes.created_at)
LIMIT 100 OFFSET 0
) a
ORDER BY date ASC;
Это занимает около 130 секунд.Без подзапросов мой запрос занимает всего 0,5 секунды.