I have following query:
SELECT
`status`, `is_client_coordinator`, id, first_name, last_name
FROM `users` `t`
WHERE t.status!="CLOSED"
and t.is_client_coordinator
or t.id in (select client_coordinator_id from projects where status not in ("DELETED", "ARCHIVED"))
ORDER BY concat(first_name, last_name)
The explain gives this:
Individually queries take less than 0.1 seconds (first one 0.04 seconds and the subquery 0.07 seconds). Put together it takes more than a second to perform the query. Both status columns are the type of ENUM. What am I doing wrong here? Any advice about how to optimize the query?
-
1could you please add create table statemets (including indexes)?NikitaSerbskiy– NikitaSerbskiy2020年05月01日 17:11:40 +00:00Commented May 1, 2020 at 17:11
-
How many rows are you expecting in the result?Rick James– Rick James2020年05月07日 21:46:54 +00:00Commented May 7, 2020 at 21:46
1 Answer 1
In order for the in clause to be evaluated, the subquery is likely being evaluated for every row. My first performance suggestion would be to use a left join and then filter:
select t.status, t.is_client_coordinator, t.id, first_name, t.last_name
from users t
left join projects p on t.client_coordinator_id = pl.id
where t.status != "CLOSED"
and t.is_client_coordinator
or (
exists(p.client_coordinator_id)
and p.status != "DELETED"
and p.status != "ARCHIVED"
)
ORDER BY concat(t.first_name, t.last_name)