1.首选要优化数据库的sql语句肯定的知道sql语句执行的计划
通过explain sql语句就可以得到具体的sql语句执行的信息
mysql> explain select * from emp where empno=123456\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: emp --->显示数据是关于那个表
partitions: NULL
type: const --->显示连接使用何种类型
possible_keys: PRIMARY --->显示可能用在这张表的索引
key: PRIMARY --->实际使用的索引
key_len: 3 --->使用索引的长度
ref: const --->显示索引那列被使用了
rows: 1 --->mysql默认必须检查用来返回的行数
filtered: 100.00
Extra: NULL -->列需要注意的返回值
2.优化的sql函数count(*),count(id)
mysql> create table t1(id int);
Query OK, 0 rows affected (0.08 sec)
mysql> insert into t1 value(1),(2),(null);
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
| NULL |
+------+
3 rows in set (0.00 sec)
mysql> select count(id),count(*) from t1;
+-----------+----------+
| count(id) | count(*) |
+-----------+----------+
| 2 | 3 |
+-----------+----------+
可以得出结论就是count(*)计算null值而count(id)不计算空值
3.子查询的优化
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
| NULL |
+------+
mysql> select * from t2;
+------+
| id |
+------+
| 1 |
| 1 |
+------+
2 rows in set (0.00 sec)
mysql> select * from t1 where t1.id in(select t2.id from t2); 显示的结果是一条数据
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> select t1.id from t1 join t2 on t1.id=t2.id; 显示的是两行数据---可以添加关键字 distinct 除去重复的数据
+------+
| id |
+------+
| 1 |
| 1 |
+------+
2 rows in set (0.00 sec)