How can I use COALESCE() in WHERE clause optimally?

倾然丶 夕夏残阳落幕 提交于 2020-01-03 18:42:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!