MySQL-count(*) 和 not in 的查询优化
文章目錄
- 生猛干貨
- 官方文檔
- 優(yōu)化的原因
- not in 的優(yōu)化
- 使用匯總表優(yōu)化count(*)查詢
- 搞定MySQL
生猛干貨
帶你搞定MySQL實戰(zhàn),輕松對應(yīng)海量業(yè)務(wù)處理及高并發(fā)需求,從容應(yīng)對大場面試
官方文檔
https://dev.mysql.com/doc/
如果英文不好的話,可以參考 searchdoc 翻譯的中文版本
http://www.searchdoc.cn/rdbms/mysql/dev.mysql.com/doc/refman/5.7/en/index.com.coder114.cn.html
優(yōu)化的原因
MySQL-Btree索引和Hash索引初探 中 什么情況下會使用到B樹索引 。
not int 和 <> 操作無法使用索引
not in 的優(yōu)化
如果not in 的指標范圍非常大的話,這個效率很差。
舉個例子
select customer_id ,first_name ,last_name ,email from customer where customer_id not in (select customer_id from payment);每個customer_id都要到payment中查詢一遍, 數(shù)據(jù)量大時很慢。
優(yōu)化后 -----------> left join
select customer_id ,first_name ,last_name ,email from customer a left join payment b on a.customer_id = b.customer_id where b.customer_id is null這樣的話,可以避免對payment表的多次查詢。
使用匯總表優(yōu)化count(*)查詢
select count(*) from product_comment where product_id = 999;如果這個表 有上億條,或者并發(fā)訪問很高的情況,這個SQL的執(zhí)行效果也不是很理想
優(yōu)化思路:就是使用匯總表
匯總表就是提前統(tǒng)計出來數(shù)據(jù),記錄到表中以備后續(xù)的查詢使用。
Step1: 建立匯總表
字段看自己的需求,基本的有下面兩列
create table product_comment_cnt(product_id int , cnt int);然后 每天定時的匯總,更新改表,對于當天新增的未統(tǒng)計到的數(shù)據(jù),可以單獨查詢,然后累加
新的SQL如下
select sum(cnt) from (# 匯總表中查詢到的由定時任務(wù)更新的數(shù)據(jù) select cnt from product_comment_cnt where product_id = 999union all # 新增的數(shù)據(jù) select count(*) from product_comment where product_id = 999 and timestr > date(now()) ) a提供思路,實際情況自行調(diào)整。
搞定MySQL
總結(jié)
以上是生活随笔為你收集整理的MySQL-count(*) 和 not in 的查询优化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL-在线处理大表数据 在线修改
- 下一篇: MySQL-分库分表初探