• 特定场景下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

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

     

  • 相关阅读:
    HDU 4691
    cin和scanf的速度差别
    一点点webservice的小知识
    Geetest 极验验证 验证图片拼图
    web api post传一个参数时 值永远是null
    关于支付宝支付的
    发布网站后只能在服务器上访问 外网访问不了??
    sidePagination: "server"和responseHandler: responseHandler
    .net 找回密码的第一步 第二步 第三步的进程条
    关于设置一个全局只读变量来实现验证
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/5936034.html
Copyright © 2020-2023  润新知