特定场景下SQL的优化
1.大表的數(shù)據(jù)修改最好分批處理。
1000萬行的記錄表中刪除更新100萬行記錄,一次只刪除或更新5000行數(shù)據(jù)。每批處理完成后,暫停幾秒中,進(jìn)行同步處理。
2.如何修改大表的表結(jié)構(gòu)。
對表的列的字段類型進(jìn)行修改,改變字段寬度時還是會鎖表,無法解決主從數(shù)據(jù)庫延遲的問題。
解決辦法:
1.創(chuàng)建一個新表。
2.在老表上創(chuàng)建觸發(fā)器同步老表數(shù)據(jù)到新表。
3.同步老表數(shù)據(jù)到新表。
4.刪除老表。
5.將新表重新命名為老表。
可以使用命令,完成上面的工作:
pt-online-schema-change –alter=”modify c varchar(150) not null default ‘’” –user=root –password=root d=sakia, t=表名 –charset=utf8 –execute
3.優(yōu)化not in 和 <> 的查詢
例子:
select customer_id ,firstname,email from customer where customer_id
not in (select customer_id from payment)
會多次查詢payment 表,如果payment表記錄很多效率將很低。
改寫后的sql
select a.customer_id ,a.firstname,a.email from customer a left join payment b
on a.customer_id=b.customer_id where b.customer_id is null;
4.對匯總表的優(yōu)化查詢
select count(1) from product_comment where product_id=999;
創(chuàng)建匯總表:
create table product_comment_cnt (product_id ,cnt int);
select sum(cnt) from (
select cnt from product_comment_cnt where product_id=999 union all
select count(1) from product_comment where product_id =999 and timestr>date(now())
) a
每天定時更新匯總表,再加上當(dāng)天的數(shù)據(jù)。
?
轉(zhuǎn)載于:https://www.cnblogs.com/yg_zhang/p/5936034.html
總結(jié)
以上是生活随笔為你收集整理的特定场景下SQL的优化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rhel6多台主机的HA集群,并实现增加
- 下一篇: JS中自定义replace可替换特殊符号