zoukankan      html  css  js  c++  java
  • 特定场景下SQL的优化

    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

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

     

  • 相关阅读:
    linux命令之------touch命令
    linux命令之------rm命令
    linux命令之------Mv命令
    linux命令之------Less命令
    linux命令之------More命令
    linux命令之------Find命令
    linux命令之------Chown命令
    linux命令之------Chmod命令
    linux命令之------Cat命令
    linux命令之------Wc命令(word count)
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/5936034.html
Copyright © 2011-2022 走看看