系统修改字符集
CentOS6:
[root@db01 ~]# vim /etc/sysconfig/i18n
CentOS7:
[root@db01 ~]# vim /etc/locale.conf
LANG="en_US.UTF-8"
数据库修改字符集
库级别的字符集
mysql> create database oldboy charset utf8;
表级别的字符集
mysql> create table mysql.oldboy(id int)charset utf8;
CREATE TABLE `student5` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生学号',
`name` varchar(20) NOT NULL COMMENT '学生姓名',
`age` tinyint(3) unsigned NOT NULL COMMENT '学生年龄',
`gender` enum('f','m') DEFAULT NULL COMMENT '学生性别',
`cometime` datetime DEFAULT CURRENT_TIMESTAMP,
`state` enum('0','1') DEFAULT '1',
PRIMARY KEY (`id`));
索引管理
索引的类型(算法)
BTREE:B树索引(Btree,B+tree,Btree)*
HASH:HASH索引
FULLTEXT:全文索引
RTREE:R树索引
B+tree算法
1.在叶子节点,添加了相邻节点的指针
2.优化了,范围查询
索引分类
* 主键索引(聚集索引)
* 普通索引
* 联合索引
* 前缀索引
* 唯一索引(唯一键)
主键:唯一 、 非空 primary key
唯一键:唯一 、 可以为空 unique key
primary key = unique key + not null
索引创建规则
1.一个字段可以创建一个索引
2.多个字段可以创建一个索引
3.多个字段可以创建多个索引,但是不能是主键
索引操作
创建主键索引 primary key
mysql> alter table student2 add primary key pri(name);
创建普通索引 index
mysql> alter table student2 add index idx_name(name);
创建唯一索引 unique key
mysql> alter table student2 add unique key uni_age(age);
如何判断,某列是否可以创建唯一索引
distinct()
count()
mysql> select count(name) from student4;
+-------------+
| count(name) |
+-------------+
| 9 |
+-------------+
1 row in set (0.00 sec)
mysql> select count(distinct(name)) from student4;
+-----------------------+
| count(distinct(name)) |
+-----------------------+
| 2 |
+-----------------------+
mysql> select count(name) from country;
+-------------+
| count(name) |
+-------------+
| 239 |
+-------------+
1 row in set (0.00 sec)
mysql> select count(distinct(name)) from country;
+-----------------------+
| count(distinct(name)) |
+-----------------------+
| 239 |
+-----------------------+
1 row in set (0.00 sec)
mysql> alter table country add unique key uni_name(name);
查看索引
mysql> show index from student2;
mysql> desc student2;
mysql> show create table student2;
删除索引
mysql> alter table student2 drop index idx_all;
mysql> alter table student2 drop index uni_age;
前缀索引
给表中数据量大的列,创建前缀索引
创建前缀索引
mysql> alter table student2 add index idx_name(name(3));
1.避免对大列建索引 2.如果有,就使用前缀索引
联合索引
性别
长相
身材
收入
年龄
爱好
...
id 名字 性别 长相 身材 身高 QQ 微信 手机 收入
mysql> create table xiangqin(id int,name varchar(10),gender enum('0','1'),face varchar(10),height int,weight int,salary int,hobby varchar(10),QQ varchar(11));
mysql> alter table xiangqin add index idx_all(gender,salary,face,weight);
联合索引,走索引情况
A:gender B:salary C:face D:weight
全部走索引:
select * from xiangqin where A;
select * from xiangqin where A B;
select * from xiangqin where A B C;
select * from xiangqin where A B C D;
部分走索引:
select * from xiangqin where A C D;
select * from xiangqin where A B D;
select * from xiangqin where A D;
全不走索引
select * from xiangqin where B C D;
select * from xiangqin where C D;
select * from xiangqin where D;