MySQL优化

来源:互联网 发布:恩施天勤网络 编辑:程序博客网 时间:2024/05/17 05:53
1.使用外键需要注意的问题
(1)MyIsam类型的表不支持外键和事务
(2)laravel框架建表语句中关于外键的使用
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('desc')->nullable()->comment('描述');
$table->unsignedInteger('user_id');
$table->string('status')->default('ok')->comment('问题状态');//可以考虑新建一张表存放状态
$table->timestamps();

$table->foreign('user_id')->references('id')->on('users');
});

}

2.SQL语句优化
(1)优化SQL语句的一般步骤
慢查询日志-》影响行数-》索引
a.通过show status命令了解各种SQL的执行频率
mysql>show [session|global] status;
session:表示当前连接(默认)
global:表示自数据库启动至今

mysql>show status;
mysql>show global status;
mysql>show status like 'Com_%' //一般查询以Com开头的 %可以是insert 、select、update、delete
mysql>show global status like 'Com_%'

只针对InnoDB存储引擎
InnoDB_rows_read 执行select操作的次数
InnoDB_rows_updated
InnoDB_rows_inserted
InnoDB_rows_deleted
mysql->show status like 'innodb_rows_%'

其他
connections mysql连接次数 mysql>show status like 'connections'
uptime 服务器工作时间(秒) mysql>show status like 'uptime'
slow_queries 慢查询次数
mysql>show variables like 'slow_queries'
mysql>show variables like '%slow%'
mysql>show variables like '%long%'
b.定位执行效率较低的SQL语句
explain select * from table_name where id = 1000;
desc select * from table_name where id = 1000;
(2)索引介绍
a.添加索引是数据库优化中最常见也是最主要的手段之一,通过添加索引可以解决大多数的SQL性能问题。需要考虑添加索引的字段(where、order by、group by、having后的字段)
b.
MyISAM类型表的数据和索引是自动分开存储的,各自是一个独立文件;InnoDB类型表的数据和索引是存储在同一个表空间里面,但可以由多个文件组成
MySQL目前不支持函数索引,但是能对列的前面某一部分进行索引,例如name字段,可以只取name的前4个字符进行索引,这个特性可以大大缩小索引文件的大小,用户在设计表结构的时候也可以对文本列根据此特性进行灵活设计
mysql>create index index_name on table_name(name(4)); //index_name:索引名 table_name:表名
(3)MySQL如何使用索引
a.索引用于快速找出在某个列中有特定值的行。对相关列使用索引是提供SELECT操作性能的最佳途径
b.对于创建的多列索引,只要查询条件中用到最左边的列,索引一般就会被使用。下面创建一个复合索引
mysql>create index index_name on table_name(field1,field2);
mysql>explain select * from table_name where field1=2006\G;//用到复合索引
mysql>explain select * from table_name where field2=2006\G//未用到复合索引
(4)使用like查询,如果like后面是%,则索引不会被用到,如下:
mysql>explain select * from table_name where field_name like "%3"\G;
a.全文检索不要使用like ‘%...%’
b.如果列添加了索引,语句中filed is null会使用索引
(5)存在但不会使用索引的情况
a.如果MySQL估计使用索引比全表扫描更慢,则不会使用索引。例如:如果列field均匀分布在1到100之间,查询时使用索引就不是很好
mysql>select * from table_name where field>1 and field<90;
b.用and或or分开的条件,前后都要求有索引,否则不会被用到
mysql>explain select * from table_name where filed=2001 or country='China'\G
c.name字段为字符串性,也添加了索引,select * from name = 123;name为整型,这种情况下就用不到索引

0 0
原创粉丝点击