mysql - 如何在 WHERE 子句中优化使用 COALESCE()?
问题描述
这是我的查询:
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
. 那么知道如何才能更优化地编写此查询吗?
解决方案
您可以使用两个单独的子查询进行计算:
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
。
推荐阅读
- r - R dplyr 逐行变异
- android - 显示对话框以要求用户在使用 Firebase Crashlytics 发生崩溃后报告崩溃
- r - 自动创建图层 ggplot
- python - Python 进程未清理以供重用
- mysql - 用表 sql, mysql 中的行位置替换字段编号
- javascript - React 应用程序中出现意外的令牌错误
- spring - 使用 Spring Data 的查询将事务设置为仅回滚,但我不知道为什么
- java - 后退按钮恢复修改后的文本视图
- sql - SQL Server:连接两个表,只获取一个表的数据,没有相同的行
- angular - Angular 材质 6.2.1 “mat-form-field-infix”覆盖宽度