Reputation: 4236
I have three tables CLASSES
, CHILD_CLASSES
, and STUDENTS
.
CLASSES
looks like this (its self referencing):
CLASS_ID | CLASS_PARENT |
-------------------------
1 | ---
2 | 1
3 | 2
CHILD_CLASSES
looks like this:
CC_ID | PARENT_CLASS_ID | CHILD_CLASS_ID
----------------------------------------
1 | 1 | 2
2 | 1 | 3
3 | 2 | 3
STUDENTS
looks like this
STU_ID | CLASS_ID | STU_NAME
----------------------------
1 | 1 | A
2 | 1 | B
3 | 2 | C
Basically the CLASSES
table is self referencing but each CLASS can also have children associated with that class. So CLASS 1 has children 2 and 3 and Class 2 has children of just 3.
So a many students can have the same class id. The students are also allowed to see all information that is a child of the class_id that is associated with them so any student with class ID of 1 can see classes 1, 2 and 3 but a student with a class idea of 2 can only see classes with ID 2 and 3. I am trying to find a query to count the number of users of a particular class that have access. so if I was looking at class_id of 1 the query would return 3 because it has two children in the CHILD_CLASSES table and then itself in the classes table. I cant seem to get this to work though, I always come up short because due to trying to count the 1 user in the CLASSES table.
the query I am using so far is this
SELECT COUNT(class_id) as TOTAL
FROM students
WHERE class_id IN (SELECT class_id
FROM child_classes
WHERE parent_class_id = 1);
Upvotes: 1
Views: 307
Reputation: 55524
Looks like child_classes
contains the same data as classes
, so the following should work:
SELECT COUNT(*)
FROM students
WHERE class_id = 1
OR class_id IN ( SELECT child_class_id
FROM child_classes
WHERE parent_class_id = 1
)
It returns the count of all students
which have class_id = 1
or are in a class which has parent_class_id = 1
.
Upvotes: 1