How can i improve my count(distinct id) query in mysql laravel 4.2 I am using three join and fetching more than 4 million records for now it is 1.5 million.

Below is my query, can you please take a look? 

SELECT count(distinct enrollments.userid) AS aggregate 
FROM users 
INNER JOIN enrollments ON users.userid = enrollments.userid 
INNER JOIN classes ON enrollments.classid = classes.classid 
INNER JOIN assigned_courses ON assigned_courses.courseid = classes.courseid 
WHERE assigned_courses.`oneroster_permission_id` = 147


Here is the explanation of my current query.
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.