如何在WHERE子句中最佳地使用COALESCE()?

时间:2018-06-16 13:48:18

标签: mysql sql query-optimization

这是我的问题:

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 个答案:

答案 0 :(得分:3)

您可以使用两个单独的子查询进行计算:

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';

索引可用于每个子查询,因此整体应该更快。顺便说一下,您不必担心NULL值,因为相关子查询中的COUNT(*)始终返回值。如果没有匹配,则值为0