MySQL-count(*) 和 not in 的查询优化
生活随笔
收集整理的這篇文章主要介紹了
MySQL-count(*) 和 not in 的查询优化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 生猛干貨
- 官方文檔
- 優化的原因
- not in 的優化
- 使用匯總表優化count(*)查詢
- 搞定MySQL
生猛干貨
帶你搞定MySQL實戰,輕松對應海量業務處理及高并發需求,從容應對大場面試
官方文檔
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
優化的原因
MySQL-Btree索引和Hash索引初探 中 什么情況下會使用到B樹索引 。
not int 和 <> 操作無法使用索引
not in 的優化
如果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中查詢一遍, 數據量大時很慢。
優化后 -----------> 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表的多次查詢。
使用匯總表優化count(*)查詢
select count(*) from product_comment where product_id = 999;如果這個表 有上億條,或者并發訪問很高的情況,這個SQL的執行效果也不是很理想
優化思路:就是使用匯總表
匯總表就是提前統計出來數據,記錄到表中以備后續的查詢使用。
Step1: 建立匯總表
字段看自己的需求,基本的有下面兩列
create table product_comment_cnt(product_id int , cnt int);然后 每天定時的匯總,更新改表,對于當天新增的未統計到的數據,可以單獨查詢,然后累加
新的SQL如下
select sum(cnt) from (# 匯總表中查詢到的由定時任務更新的數據 select cnt from product_comment_cnt where product_id = 999union all # 新增的數據 select count(*) from product_comment where product_id = 999 and timestr > date(now()) ) a提供思路,實際情況自行調整。
搞定MySQL
總結
以上是生活随笔為你收集整理的MySQL-count(*) 和 not in 的查询优化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL-在线处理大表数据 在线修改
- 下一篇: MySQL-分库分表初探