I have an SQL (MariaDB, version: 10.3.22-MariaDB-0+deb10u1):
SELECT
v.employee_id AS id,
REPLACE(
FORMAT(
COALESCE((
SUM(COALESCE((COALESCE(v.amount, 0) / COALESCE(ash.value, a.standard, 0)), 0))
/
(
SUM(COALESCE(v.worktime, 0))
+
(
SELECT SUM(COALESCE(t.break, 0))
+ COALESCE(SUM(t.assigned_task1), 0)
+ COALESCE(SUM(t.assigned_task2), 0)
+ COALESCE(SUM(t.assigned_task3), 0)
+ COALESCE(SUM(t.assigned_task4), 0)
+ COALESCE(SUM(t.assigned_task5), 0)
FROM times t
WHERE t.employee_id = v.employee_id
AND t.day BETWEEN '2022-02-03' AND '2022-02-03'
)
)
), 0) * 100
, 0
), ',', '') AS p_real
FROM volumes v
INNER JOIN activities a
ON
v.activity_id = a.id
AND a.is_deleted = 0
AND a.id IN (-1, 145, 218, 227, 286) /* There are much more IDs in real SQL. */
LEFT JOIN activity_standard_histories ash
ON ash.activity_id = a.id AND ash.created = (
SELECT created
FROM activity_standard_histories
WHERE
DATE(activity_standard_histories.created) <= v.day
AND activity_standard_histories.activity_id = a.id
ORDER BY activity_standard_histories.created DESC
LIMIT 1
)
WHERE
v.employee_id IN ('552','553','554','2113','2991') /* There are much more employee_ids in real SQL. */
AND v.day BETWEEN '2022-02-03' AND '2022-02-03'
GROUP BY v.employee_id
volumes
table has 486.2Mb size and growth up all the time.
This query is performed for a very long time. What I've noticed:
Tables indexes:
I've seen a lot of sources: this, this, this, this and so on. However, I'm not sure what exactly should I apply. Maybe it could be some additional complex index, but I'm not sure which one, given that each table already has certain indexes.