We have a registration system Database and basically what this query does is check the students that are in the class so that they can be selected to be marked as absent if they are absent. For some reason, it takes 30 seconds. Does anybody know why?
FROM Stdts
LEFT JOIN StdtReg ON StdtReg.StdtID = Stdts.ID
LEFT JOIN usrs ON StdtReg.userID = usrs.ID
WHERE (SELECT ID FROM ClssInstncEnrol cie WHERE cie.status = 0 AND classInstanceID={$_GET['ci']} AND StdtID = Stdts.ID LIMIT 1) IS NOT NULL
OR (SELECT ID FROM DropIns di WHERE di.type <> -1 AND classInstanceID= {$_GET['ci']} AND StdtID = Stdts.ID LIMIT 1) IS NOT NULL
AND (CONCAT(Stdts.firstName, ' ', Stdts.lastName) OR CONCAT(usrs.firstName,' ', usrs.lastName))
ORDER BY firstName, lastName
Run the query with “EXPLAIN ” before it and it will tell you how each table is being joined and where you might be missing an index.
Also, you have an SQL injection waiting to happen with queries of this form with HTTP params interpolated directly in the query.
Finally, you’ve left off some of the query and the schema, but this strikes me as something that could be done with joins rather than subselects, or even as separate queries to generate the list of student ids more efficiently before you even run the main query.