SQL query to list all student users, add column to show who were logged in at least once
Looks like your trying to see if a record for the userid exists in the mdl_user_lastaccess table, you can achieve that with a left join, try this

select u.*,
       case
       when ul.userid is null then 0
       else 1
       end loggedin
  from mdl_user u
  join mdl_role_assignments ra
    on u.id = ra.userid
  left join (
     select ula.userid
       from mdl_user_lastaccess ula
      group by ula.userid
) ul
on u.id = ul.userid


Another approach using the exists statement

select u.*,
       1 as loggedin
  from mdl_user u
  join mdl_role_assignments ra
    on u.id = ra.userid
 where exists (
    select 1
      from mdl_user_lastaccess ul
     where u.id = ul.userid
 )

union

select u.*,
       0 as loggedin
  from mdl_user u
  join mdl_role_assignments ra
    on u.id = ra.userid
 where not exists (
    select 1
      from mdl_user_lastaccess ul
     where u.id = ul.userid
 )