sql查询与索引
背景:有以下一个查询语句
SELECT b.id , b.product_name,b.generate_time,b.expiry_date,b.uid,b.query_times,b.state FROM product_bottle b where 1=1 and b.product_name LIKE concat('%',?,'%') and b.state = ? limit ?,?
查询很慢,刚开始不知道为什么,前辈说这样让索引无用武之地。
在bottle表中,存在product_name,但同时也存在product_id 。所以即使需求是根据name来查询,自己也应该通过转换来使用索引id来查询。
索引:索引是一种增强式的存在,这意味着,即使没有索引,SQL仍然可以实现应有的功能。
方法1:
SELECT * FROM ( SELECT b.id ,b.specification_id, b.product_name,b.generate_time,b.expiry_date,b.uid,b.query_times,b.state FROM product_bottle b LEFT JOIN `account_user` u ON u.id = b.`uid` <if test="productName != null"> AND b.`product_name` LIKE CONCAT('%',#{productName},'%') </if> LIMIT 1000 ) lists
方法2:
SELECT * FROM ( SELECT b.id ,b.specification_id, b.product_name,b.generate_time,b.expiry_date,b.uid,b.query_times,b.state FROM product_bottle b where 1=1 <if test="id != null"> and b.id = #{id} </if> <if test="state != null"> and b.state = #{state} </if> <if test="produceDateStart != null"> and b.generate_time >= #{produceDateStart} </if> <if test="productId != null"> and b.specification_id in <foreach collection="productId" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="uid != null"> and b.uid IN <foreach collection="uid" item="userId"> #{userId} </foreach> </if> limit 500 ) select_bottle
如下方法1与方法2 的对比结果:
在数据量越来越大的情况下,使用索引性能提升越明显。