我如何优化我的MySQL查询?
SELECT a.*, u.avatar, u.name, u.surname, u.username, COUNT(a.user1) AS cnt
FROM user_actions a,users u,following f
WHERE a.user1=u.user_id AND
a.user1=f.follower_id AND
f.user_id=159
GROUP BY a.user1, a.action, day(a.dt)
ORDER BY a.id DESC
LIMIT 7;
查询耗时4.4909秒
表user_actions的索引:
Action Keyname Type Unique Packed Column Cardinality Collation
Edit PRIMARY BTREE Yes No id 516094 A
Edit user1 BTREE No No user1 15639 A
Edit user2 BTREE No No user2 36863 A
Edit action BTREE No No action 16 A
Edit dt BTREE No No dt 516094 A
Edit group_index BTREE No No user1 20643 A
EXPLAIN SELECT a . * , u.avatar, u.name, u.surname, u.username, COUNT( a.user1 ) AS cnt
FROM user_actions a, users u, following f
WHERE a.user1 = u.user_id
AND a.user1 = f.follower_id
AND f.user_id =159
GROUP BY a.user1, a.action, day( a.dt )
ORDER BY a.id DESC
LIMIT 7
id select_type表类型possible_keys key key_len ref行额外1 SIMPLE f ref user_id,follower_id,for_actions for_actions 4 const 242使用index; 使用临时; 使用filesort 1 SIMPLE a ref user1,group_index group_index 4 pictify_main.f.follower_id 25 1 SIMPLE u eq_ref PRIMARY PRIMARY 4 pictify_main.a.user1 1使用where
由于格式化无法理解您的索引
但是下面的索引可以帮助..
user_actions(user1)
following (user_id)
users(user_id)
否则如建议,请张贴解释计划。
非确定性GROUP BY:SQL检索既不在聚合函数中也不在GROUP BY表达式中的列,因此这些值在结果中将是非确定性的。
SELECT *:使用*通配符选择所有列将导致查询的含义和行为在表的模式更改时发生更改,并可能导致查询检索太多数据。
不使用AS关键字的别名在列或表别名中显式使用AS关键字(如“tbl AS别名”)比隐含别名(如“tbl别名”)更具可读性。
我会反转一些,因为你正在寻找一个特定的“跟随”用户ID ...然后添加“STRAIGHT_JOIN”子句告诉MySQL按照明确列出的顺序
确保表索引关注的索引(User_ID,Follower_ID)用户(User_ID)User_Actions(User1,Action,Dt,ID)
select STRAIGHT_JOIN
UA.*,
U.Avatar,
U.Name,
U.SurName,
U.UserName,
count(*) as UserActionsCount
from
Following F
JOIN User_Actions UA
on F.Follower_ID = UA.User1
Join Users U
on UA.User1 = U.User_ID
where
F.User_ID = 159
group by
F.Follower_ID,
UA.Action,
Day( UA.Dt )
order by
UA.ID DESC
limit
7
链接地址: http://www.djcxy.com/p/93605.html