In case you have your own slow SQL query, you can optimize it automatically here.
For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `threes` ADD INDEX `threes_idx_updated_at` (`updated_at`);
ALTER TABLE `threes` ADD INDEX `threes_idx_deleted_at_threeable_threeable` (`deleted_at`,`threeable_id`,`threeable_type`);
ALTER TABLE `twos` ADD INDEX `twos_idx_id` (`id`);
SELECT
twos.id,
threes.id
FROM
(SELECT
twos.id twoId,
MAX(th.updated_at) threeMaxUA
FROM
twos
LEFT JOIN
(
SELECT
th.*
FROM
(SELECT
threes.threeable_id,
threes.threeable_type,
MAX(updated_at) AS updated_at
FROM
threes
WHERE
threes.deleted_at IS NULL
GROUP BY
threes.threeable_id,
threes.threeable_type
ORDER BY
NULL) thmax
LEFT JOIN
threes pr
ON (
th.threeable_id = thmax.threeable_id
AND th.updated_at = thmax.updated_at
AND th.threeable_type = thmax.threeable_type
)
GROUP BY
th.threeable_id,
th.threeable_type
ORDER BY
NULL) th
ON ((th.threeable_id = twos.id
AND th.threeable_type = 'App\\Two')
OR (th.threeable_id = twos.product_id
AND th.threeable_type = 'App\\One'))
GROUP BY
twos.id
ORDER BY
NULL
) twthmax
LEFT JOIN
twos
ON twos.id = twthmax.twoId
LEFT JOIN
threes
ON (
twthmax.threeMaxUA = threes.updated_at
AND (
(
threes.threeable_id = twos.id
AND threes.threeable_type = 'App\\Two'
)
OR (
threes.threeable_id = twos.product_id
AND threes.threeable_type = 'App\\One'
)
)
)