I have tables called: activities and deficiencies.
activities table contains all activities registered by students. deficiencies table contains all deficiencies that the students might get due to the registered activity.
Here are the table structures with sample data:
activities table
activityid title
-------------------------------------------------------------
1 Student Retreat
2 Student Orientation
deficiencies table
deficiencyid activity_id deficiency status
-------------------------------------------------------------
1 1 NARRATION CLEARED
2 1 PHOTO CLEARED
3 1 REPORT CLEARED
4 2 NARRATION WAITING
5 2 PHOTO CLEARED
6 2 REPORT WAITING
For each activity entry, there will be three rows in the deficiencies table. I want to be able to list each activity once if all the statuses of the items listed there are already CLEARED. So if one or more is still WAITING – they don’t get listed in the query.
I was attempting to do this using this query but I couldn’t get any lucky:
SELECT * FROM deficiencies,activities WHERE status='CLEARED' AND activityid=activity_id AND COUNT(deficiencyid)=3 GROUP BY activity_id ORDER BY deficiencyid ASC
I was getting the following from MySQL:
Invalid use of group function
The output I was expecting is the first record in the activities table.
What could be the best solution using only one query without multiple SELECT in SELECT in another SELECT sub-queries? There will be thousands of records in the tables so I’m hoping that the most efficient query can be used.
If you want to do this with a JOIN:
This JOINs the activity and deficiencies tables, filters out the records other than CLEARED, groups by activity, and the filters out the groups that do not have exactly three records in them.
It requires that the data is guaranteed to be as you described it (always three deficiency records). I wrote the GROUP BY to avoid using the MySQL extension allowing non-grouped, non-aggregated columns to be selected. Also, I assume that there’s also a studentid field involved which you left out for the sake of clarity, otherwise this whole system will support only a single student.