MySQL基本应用

1.默认类型转换

CREATE TABLE `indextest` (
`id` int(10)  AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
 PRIMARY KEY (`id`),

 KEY `idx_name` (`name`),

)

explain select age from indextest where name=‘111222’ \G显示的是使用索引idx_name

而使用explain select age from indextest where name=111222 \G显示的是全表扫描,未使用索引。

name字段定义为varchar,查询时需要加上引号,否则可能会引起索引失效,变为全表扫描。

反过来,explain select age from indextest where id ='3' \G,mysql会很好的转换,不会引起索引失效。

 

2.覆盖索引

CREATE TABLE `user_group` (
`id` int(10)  AUTO_INCREMENT,
`uid` int(10) not null,

'group_id' int(10) not null,
 PRIMARY KEY (`id`),

 KEY `uid` (`uid`),

 KEY `group_id` (`group_id`),

)

explain select sql_no_cache uid from user_group where group_id =234 \G,explain的结果是const,查询速度较慢

加上联合索引:alter table user_group add index group_id_uid(group_id,uid);查询效率会大幅度提升。

explain的extra结果是using index,表明查询使用的是覆盖索引。

覆盖索引是在MySQL在检索索引时就直接返回数据而不是通过索引检索数据。

需要注意的是复合索引index(a,b,c),a或(a,b)会使用索引,而b或(b,c)不会使用索引。

 

3.一定要对用户的输入进行校验,否则可能会有意想不到的结果

假设编写的sql中含有如下:

where username = ? and password = ?

而username字段输入的是admin;

密码就被省略了。校验工作一定要由自己完成。

使用PreparedStatement就可以完成对SQL注入的检查。

 

4.没有使用UTF-8,放到有些语言环境下程序就无法正常的工作了

posted on 2014-04-20 20:08  lnlvinso  阅读(223)  评论(0编辑  收藏  举报