SELECT ue.id, u.id AS userid, ul.timeaccess, u.firstnamephonetic,u.lastnamephonetic,u.middlename,u.alternatename,u.firstname,u.lastname, u.email, u.city, u.lastaccess,
                                      c.fullname, c.shortname,
                                      (SELECT r.name
                                         FROM {user_enrolments} ue2
                                         JOIN {enrol} e ON e.id = ue2.enrolid
                                         JOIN {role}  r ON e.id = r.id
                                        WHERE ue2.userid = u.id
                                          AND e.courseid = c.id ) AS rolename
                                 FROM {user_enrolments} ue
                                 JOIN {enrol}  e ON e.id = ue.enrolid
                                 JOIN {course} c ON c.id = e.courseid
                                 JOIN {user}   u ON u.id = ue.userid
                                 LEFT JOIN {user_lastaccess} ul ON ul.userid = u.id
                                WHERE ul.timeaccess IS NULL