记录一次mysql优化
一次分页情况下,发现查询数据很快,统计却很慢,要一分钟以上,explain得出:
explain
select count(*) from `user` u left join organization_identity oi on u.id = oi.uid
left join admin a on u.aid=a.id left join department d on a.department_id =d.id
where u.`type` =1 and u.status=0
|id |select_type|table|partitions|type |possible_keys |key |key_len|ref |rows |filtered|Extra |
|---|-----------|-----|----------|------|-----------------------------------|-----------------------|-------|----------------|------|--------|---------------------------------------------------------------|
|1 |SIMPLE |u | |ALL | | | | |263535|1.0 |Using where |
|1 |SIMPLE |oi | |eq_ref|u_uid,IDX_Organization_Identity_Uid|u_uid |146 |xxx.u.id|1 |100.0 |Using index |
|1 |SIMPLE |a | |index | |IDX_Admin_Department_Id|111 | |1314 |100.0 |Using where; Using index; Using join buffer (Block Nested Loop)|
|1 |SIMPLE |d | |eq_ref|PRIMARY |PRIMARY |146 |func |1 |100.0 |Using where; Using index |
从数据量和type来看,主要是u标和a表影响的,又发现如果有筛选项,查询效率还可以,而left join a和d表不查询极慢,故而想到一个处理方法。
在mybaitis中做查询修改,在没有筛选a和d表的情况下,用if把这个俩个连接去掉。这样就完成了不筛选的情况下,速度从60s+变成了1s+。
注: user表将近30W,其他表数据还好,关联筛选的问题。