查询使用索引相关
1, 避免在 sql 的 where 条件中使用 函数,会导致索引失效
2, join 两个表时,如果关联字段数据类型不一致,请使用类型转换函数。
3, sql 中的条件值必须与字段类型一致, 避免数据库做隐式类型转换,导致索引失效 (数据类型禁止加引号,字符串必须加引号).
4, 避免使用 左模糊 ( like '%xxx' ), 全模糊查询。 尽量 使用 右模糊查询,可以走索引。
5, join , in , not in , exists , not exists 性能比较
A, 字段上有索引: exists(好) -- in 差-- join 最差
B, 字段上无索引 : join 好 -- exists 差 -- in 最差
C, 字段上有索引 : left join 好--- not exists 差 -- not in 最差
D, 字段上无索引 : not in 好 --- not exists 差 -- left join 最差
6, 尽量不要使用 反向查询, 例如 not in , != , not like 它们不走索引
7, 尽量不要or , 不走索引 , 如果可以用 in 代替, in 元素个数要严格控制, 防止 超额,建议 最大不超过 200
8, 日期字段查询统一使用 这种格式的字符串 "yyyy-MM-dd HH:mm:ss" ; mysql 的日期类型与字符类型相同的,不需要做额外的类型转换。 比如 select id where time >='2010-01-10 01:10:20'
9, 避免多于排序:使用 group by 时,数据库默认是会进行排序操作的,如果 不需要,可以使用 group by NULL 避免数据库排序(提升查询效率和 减少资源开销) select id form user group by name order by NULL ;
- 业务程序禁止使用 存储过程, 触发器,函数,作业和视图等, 一些特殊日期, 聚合等函数除外。
11, 尽量使用 join 连接查询 代替子查询
12, 所有内连接, 需将 关联表统一写到 from 子句中,关联条件和过滤条件统一写到 where 子句中
13, 外连接都用 left join ,不用 right join
-
多表连接的分页语句,如果 过滤条件在单个表上, 需要先分页再 join 连接 比如 : select a.name ,b.id from ( select id,name from user where id>100 order by id limit 0,10 ) a inner join shop b where a.id = b.id;
-
在 iBatis 中,尽量不要使用 $name$ , 应该采用 #name# 防止sql注入
-
inser into 语句也必须指定具体字段名称。 禁止写成 insert into user values(...)
-
SQL 中 尽量避免出现 now() , rand() , sysdate() , current_user() 等不确定结果的函数
-
禁止用 select for update 语法
其他知识
1, insert ignore into 当 插入 数据时,如出现错误,重复数据, 将不返回错误,只以经过形式返回。所以使用 ignore 请确保语句本身没有问题,否则也会被忽略掉 比如:
insert ignore into books(name) valuse ('xxx');
2, on duplicate key update 当 primary 或者 unique 重复时, 则执行 update 语句,在原有记录基础上,更新指定字段内容, 其他字段内容保留,如果 update 后为无用语句,如id =id ,错误不会被忽略,为了实现 name 重复的数据插入不报错,可使用 下语句:
insert into books(name) values 'xxx' on duplicate key update id=id ;
3, insert ... select ... where not exist 根据 select 的条件判断是否插入, 可以不光通过 primary 和 unique来判断, 也可以通过其他条件
insert into books(name) select id from dual where not exists (select id from books where id=1)
4, replace into 如果存在 primary or unique 相同的记录, 则先删除再插入新的记录。 如果记录有多个字段,在插入的时候如果有的字段 没有赋值,那么新插入的记录字段为空
replace into books select 1 from books
以上 来自 书籍 BAT 公司员工的MYSQL 修为