我的问题是:
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';
正如您所知道的,mysql优化器永远不能在这个服务器上使用索引 coalesce(qa.related, qa.id) = vi.question_id
. 那么,你知道我怎样才能把这个查询写得更优化吗?
1条答案
按热度按时间jum4pzuy1#
可以使用两个单独的子查询进行计算:
索引可以用于每个子查询,因此总体上应该更快。顺便说一下,你不用担心
NULL
价值观,因为COUNT(*)
在相关子查询中,总是返回一个值。如果没有匹配项,则值为0
.