写一手好 SQL 很有须要
List<Integer> batchIdList = queryList('select id FROM `coupon` WHERE expire_date <= #{currentDate} and status = 1 limit #{(pageNo-1) * PAGE_SIZE},#{PAGE_SIZE}'); if (CollectionUtils.isEmpty(batchIdList)) { return; } update('update status = 0 FROM `coupon` where status = 1 and id in #{batchIdList}') pageNo ++; } 操纵符<>优化 凡是<>操纵符无法行使索引,举譬喻下,查询金额不为100元的订单:select id from orders where amount != 100;假如金额为100的订单少少,这种数据漫衍严峻不均的环境下,有也许行使索引。鉴于这种不确定性,回收union聚合搜刮功效,改写要领如下: (select id from orders where amount > 100) union all(select id from orders where amount < 100 and amount > 0) OR优化 在Innodb引擎下or无法行使组合索引,好比: select id,product_name from orders where mobile_no = '13421800407' or user_id = 100; OR无法掷中mobileno + userid的组合索引,可回收union,如下所示: (select id,product_name from orders where mobile_no = '13421800407') union(select id,product_name from orders where user_id = 100); 此时id和product_name字段都有索引,查询才最高效。 IN优化 IN得当主表大子表小,EXIST得当主表小子表大。因为查询优化器的不绝进级,许多场景这两者机能差不多一样了。 实行改为join查询,举譬喻下:select id from orders where user_id in (select id from user where level = 'VIP'); 回收JOIN如下所示: select o.id from orders o left join user u on o.user_id = u.id where u.level = 'VIP'; 不做列运算 凡是在查询前提列运算会导致索引失效,如下所示:查询当日订单 select id from order where date_format(create_time,'%Y-%m-%d') = '2019-07-01'; date_format函数会导致这个查询无法行使索引,改写后: select id from order where create_time between '2019-07-01 00:00:00' and '2019-07-01 23:59:59'; 停止Select all 假如不查询表中全部的列,停止行使 SELECT *,它会举办全表扫描,不能有用操作索引。 Like优化 like用于恍惚查询,举个例子(field已成立索引): (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |