1 正则 regexp 比like更消耗资源
select name, email from t where email REGEXP "@163[.,]com$"
select name, email from t where email like "%@163.com" ro email like "%@163,com"
2 RAND() 提取随机行
和order by一起使用,能把数据随机排序
select * from t order by rand() limit 5, 随机抽取5行数据
3 利用group by 的 with rollup
with rollup 相比group by能聚集更多信息
select * , count(pname) from demo group by cname,pname with rollup
4 外键
Innodb支持外键 myisam不支持外键, 不鼓励使用外键
foreign key(id) references outTable(id) on delete cascade on update cascade;
优化
1 show 【session|global】status 各种SQL执行频率
session 默认 当前连接 global 数据库启动以来
SHOW STATUS LIKE "Com_select";
SHOW STATUS LIKE "connections" 连接mysql数量
uptime 工作秒数 slow_queries 慢查询次数
2 定位效率较低的sql语句
慢查询日志 show variables like "%slow";
3 对sql语句经行解析 explain desc
expline/desc select * from t;
看影响行数
索引的使用
1 like查询 %不再第一个字符,用到索引
2 is (not ) null 使用索引
3 or and 前后都要加索引 才会用到索引
4 尽量避免使用嵌套查寻 select from where id in(select from ) 外面不会用到索引 ,连接使用索引,使用连接 select * from t1 , t2 where
查看索引的使用情况
show status like "Handler_read%"
Handler_read_rnd_next 值高,需要建立索引
表优化
检查表: check
check table 表名 检测一个或多个表是否有错
定期优化: optimize
optimize table 表名 如过已经删除表的一大部分,使用这个命令将表空间碎片合并
insert 语句优化
insert 插入多项值,避免每插入一次连接一次数据库
group by
如果需要,关掉排序 group by id order by null;
in 嵌套查询
不要用 select from where id in(select from ) 外面不会用到索引 ,连接使用索引,使用连接 select * from t1 , t2 where
多使用中间表
视图:来表示热门贴
多用枚举
服务器优
1 字符集
服务器,数据库 客户端 连接字符集 --- utf-8
配置文件 default-character-set=utf-8 客户端 连接
character-set-server=utf-8 服务器 数据库
collation-server=utf-8_general_ci 校验字符集
2 改密吗
1 关进程pkill mysql
2 跳过授权表 mysql --skip-grand-tables --user=mysql&
3 登录mysql bu用密码
4 修该密码 update user set password=password("wei") where user = "root" and host="localhost"
5 再次登录