问题
Here is my query:
select coalesce(qa2.subject, qa.subject) as question_subject,
qa.body,
(select count(*)
from viewed_items vi
where coalesce(qa.related, qa.id) = vi.question_id
) as total_question_viewed
from questions_and_answers qa
left join questions_and_answers qa2 on qa.related = qa.id
where body like ':entry';
As you know, MySQL optimizer can never use a index on this on coalesce(qa.related, qa.id) = vi.question_id
. So any idea how can I write this query more optimal?
回答1:
You can do the calculation with two separate subqueries:
select coalesce(qa2.subject, qa.subject) as question_subject,
qa.body,
( (select count(*)
from viewed_items vi
where qa.related = vi.question_id
) +
(select count(*)
from viewed_items vi
where qa.related is null and qa.id = vi.question_id
)
) as total_question_viewed
from questions_and_answers qa left join
questions_and_answers qa2
on qa.related = qa.id
where body like ':entry';
Indexes can be used for each subquery, so it should be faster overall. By the way, you don't have to worry about NULL
values, because COUNT(*)
in a correlated subquery always returns a value. If nothing matches, the value will be 0
.
来源:https://stackoverflow.com/questions/50888481/how-can-i-use-coalesce-in-where-clause-optimally