查询在子查询中缓慢运行

时间:2017-01-09 16:12:37

标签: mysql

此查询在子查询中缓慢进行。我还没有访问临时表的权限,但无论如何还要进一步优化这个查询,还是我在某个地方使用破坏的逻辑?

SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT 
       CONCAT( u.firstname , ' ' , u.lastname) as Student_name,
        u.id as Student_ID,
        FROM_UNIXTIME(u.firstaccess) as first_moodle_access,
        FROM_UNIXTIME(u.lastaccess) as last_moodle_access,
        FROM_UNIXTIME(last.timeaccess) as last_course_access,
        grp.name as Cohorts,
        cour.fullname as course 
FROM 
mdl_user as u 
Inner Join mdl_user_lastaccess as last on u.id = last.userid
Inner Join mdl_course as cour on last.courseid = cour.id
Inner Join mdl_groups as grp on cour.id = grp.courseid 
WHERE u.lastlogin = (
                     Select Max(u2.lastlogin)
                     From mdl_user as u2 
                     where u2.lastlogin = u.lastlogin
                    ) 
AND cour.id = '10189' AND 
u.firstaccess > '0' AND 
u.lastaccess > '0';

1 个答案:

答案 0 :(得分:0)

相关子查询在大多数情况下效率非常低,您可以使用已交付的表获得更好的性能。 大多数情况下,可以使用INNER JOIN重写相关子查询。

我认为您的相关子查询可以重写如下,但您需要检查结果是否相同,因为我不知道您的表结构和数据。

SELECT 
       CONCAT( u.firstname , ' ' , u.lastname) as Student_name,
        u.id as Student_ID,
        FROM_UNIXTIME(u.firstaccess) as first_moodle_access,
        FROM_UNIXTIME(u.lastaccess) as last_moodle_access,
        FROM_UNIXTIME(last.timeaccess) as last_course_access,
        grp.name as Cohorts,
        cour.fullname as course 
FROM 
mdl_user as u 
Inner Join mdl_user_lastaccess as last on u.id = last.userid
Inner Join mdl_course as cour on last.courseid = cour.id
Inner Join mdl_groups as grp on cour.id = grp.courseid 
Inner Join(
  Select
    Max(lastlogin)
  FROM
    mdl_user
) AS u2
ON 
  u.lastlogin = u2.lastlogin
WHERE
cour.id = '10189' AND 
u.firstaccess > '0' AND 
u.lastaccess > '0';