记一次mysql语句调优(关于select ... in ()问题)

记一次mysql语句调优(关于select … in ()问题)

示例

表索引

  • 原sql语句
    explain select * from cap_info a where a.id in (select max(id) from cap_info b where b.cap_mode != ‘’ group by b.cap_id, b.cap_type, b.cap_mode);
    原sql语句索引使用* 改进sql语句
    select * from cap_info a inner join (select max(id) maxId from cap_info where cap_mode != ‘’ group by cap_id, cap_type,cap_mode ) b on a.id=b.maxId;
    改进sql语句索引使用

原理解析

in的用法注意点

select * from a where id in (select id from b);
该语句对于b表使用索引,对于a表使用全表扫描
有点类比于select * from a where exists(select id from b where a.id = b.id);
exists根据其子句(即内查询,select id from b where a.id = b.id)的结果集是否为空,返回一个布尔值。该语句效果就是查询外表(即a表)的每一行,带入内查询作为检验,如果内查询为非空(即exists子句返回ture,则这一行作为外查询的结果行)。

几种join用法

(inner)join:只有当两表都有这个id时,这条数据才会显示
left join:显示join子句左边的表的所有行
right join:显示join子句右边的表的所有行
full join(mysql不支持):结合左联和右联的所有结果

join示例

示例结果
user表
±—±---------±---------+
| id | userName | password |
±—±---------±---------+
| 1 | 张三 | 123 |
| 3 | 李四 | 123 |
| 5 | 王二 | 123 |
| 7 | 祁一 | 123 |
±—±---------±---------+
user_info表
±—±----±----±--------+
| id | sex | age | user_id |
±—±----±----±--------+
| 1 | boy | 25 | 1 |
| 3 | boy | 27 | 3 |
| 5 | boy | 30 | 5 |
| 7 | boy | 32 | 6 |
±—±----±----±--------+
mysql> select * from user join user_info on user.id = user_info.user_id;
±—±---------±---------±—±----±----±--------+
| id | userName | password | id | sex | age | user_id |
±—±---------±---------±—±----±----±--------+
| 1 | 张三 | 123 | 1 | boy | 25 | 1 |
| 3 | 李四 | 123 | 3 | boy | 27 | 3 |
| 5 | 王二 | 123 | 5 | boy | 30 | 5 |
±—±---------±---------±—±----±----±--------+
3 rows in set (0.00 sec)

mysql> select * from user left join user_info on user.id = user_info.user_id;
±—±---------±---------±-----±-----±-----±--------+
| id | userName | password | id | sex | age | user_id |
±—±---------±---------±-----±-----±-----±--------+
| 1 | 张三 | 123 | 1 | boy | 25 | 1 |
| 3 | 李四 | 123 | 3 | boy | 27 | 3 |
| 5 | 王二 | 123 | 5 | boy | 30 | 5 |
| 7 | 祁一 | 123 | NULL | NULL | NULL | NULL |
±—±---------±---------±-----±-----±-----±--------+
4 rows in set (0.00 sec)

mysql> select * from user right join user_info on user.id = user_info.user_id;
±-----±---------±---------±—±----±----±--------+
| id | userName | password | id | sex | age | user_id |
±-----±---------±---------±—±----±----±--------+
| 1 | 张三 | 123 | 1 | boy | 25 | 1 |
| 3 | 李四 | 123 | 3 | boy | 27 | 3 |
| 5 | 王二 | 123 | 5 | boy | 30 | 5 |
| NULL | NULL | NULL | 7 | boy | 32 | 6 |
±-----±---------±---------±—±----±----±--------+
4 rows in set (0.00 sec)

猜你喜欢

转载自blog.csdn.net/qq_28376741/article/details/86506919