You can speed this up by adding indexes. I would suggest: planning_requests(id_tr, trainer)
.
You can do this as:
create index planning_requests_id_trainer on planning_requests(id_tr, trainer);
Also, I think you are missing an =
in the first subquery.
EDIT:
If you have a lot of duplicate values of id_tr
, then in addition to the above indexes, it might make sense to phrase the query as:
select id_tr
from (select distinct id_tr
from planning_requests
) a
where . . .
The where
conditions are being run on every row of the original table. The distinct
is processed after the where
.