你的位置:首页 > 软件开发 > 数据库 > 特定场景下SQL的优化

特定场景下SQL的优化

发布时间:2016-10-07 16:00:13
1.大表的数据修改最好分批处理。 1000万行的记录表中删除更新100万行记录,一次只删除或更新5000行数据。每批处理完成后,暂停几秒中,进行同步处理。 2.如何修改大表的表结构。 对表的列的字段类型进行修改,改变字段宽度时还是会锁表,无法解决主从数据库延迟的问题。 解 ...

1.大表的数据修改最好分批处理。

1000万行的记录表中删除更新100万行记录,一次只删除或更新5000行数据。每批处理完成后,暂停几秒中,进行同步处理。

2.如何修改大表的表结构。

对表的列的字段类型进行修改,改变字段宽度时还是会锁表,无法解决主从数据库延迟的问题。

解决办法:

1.创建一个新表。

2.在老表上创建触发器同步老表数据到新表。

3.同步老表数据到新表。

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.优化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.对汇总表的优化查询

select count(1) from product_comment where product_id=999;

创建汇总表:

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

每天定时更新汇总表,再加上当天的数据。

 


原标题:特定场景下SQL的优化

关键词:sql

sql
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。