How can i improve my count(distinct id) query in mysql laravel 4.2
See if this gives you the right answer:

SELECT  COUNT(DISTINCT userid) AS aggregate
    FROM  enrollments AS e
    WHERE  EXISTS 
      ( SELECT  *
            FROM  classes AS c
            JOIN  assigned_courses AS ac ON ac.courseid = c.courseid
            WHERE  ac.oneroster_permission_id = 147
              AND  c.classid = e.classid 
      ) AS x


Note:  I tried to avoid the DISTINCT by avoiding any JOINs.  JOINs tend to explode the number of rows, only to force you to use GROUP BY or DISTINCT to get back to what you wanted.  But, I guess there could be multiple occurences of a userid in enrollments. 

No matter how it is written, I think the performance will be poor.  Notice how the query needs to come at it from two sides, one to filter on 147, the other to connect to enrollments.classid.