SQL-I想减少执行时间

时间:2013-06-27 10:35:31

标签: mysql sql

SELECT DATE_FORMAT( max(login_time),'%Y-%m-%d') from 
aaa AS b,user AS a where b.user_id = a.user_id
GROUP BY b.user_id ORDER BY b.user_id 

3 个答案:

答案 0 :(得分:0)

SELECT DATE_FORMAT(max(a.login_time), '%Y-%m-%d')    
FROM aaa AS a,
JOIN user b
ON b.user_id = a.user_id
GROUP BY b.user_id ORDER BY b.user_id 

或仅按日期

SELECT DATE_FORMAT(max(a.login_time), '%Y-%m-%d')    
FROM aaa AS a

然后在INDEX上加login_time,如果还没有,则在user_id上加上

CREATE INDEX idx_login_time ON aaa(login_time) USING BTREE;

答案 1 :(得分:0)

useruser_id上提供login_time综合索引:

alter table user add index (user_id, login_time);

这将用于优化与aaa的联接,并查找每个用户的最长登录时间。

要充分利用此索引,可能需要在子查询中获取最大值:

select date_format(max_login, '%Y-%m-%d')
from aaa as b
join (select user_id, max(login_time) max_login
      from user
      group by user_id) a
on a.user_id = b.user_id
order by b.user_id

答案 2 :(得分:0)

首先,这是一个恰当的陈述:

SELECT DATE_FORMAT(max(login_time),'%Y-%m-%d')
    FROM user AS u
    INNER JOIN aaa AS a
       ON u.user_id = a.user_id
    GROUP BY a.user_id
    ORDER BY a.user_id
  • 如果使用InnoDB改善性能,则在login_time上添加索引。
  • 尝试通过设置WHERE子句来缩小所选日期(例如,仅显示活动用户[其中u.status ='active'])
  • 您还可以通过在语句末尾设置限制来限制显示的记录,例如LIMIT 10