views:

110

answers:

1

You can also write hibernate hql or criteria queries.

I have Teacher entity and Student entity like this :

class Teacher {
     public Long id ;
     public Set<Student> students;
} 

class Student {
    public Long id ;
    public Teacher teacher ;
    public Boolean passedSemester1;  
    public Boolean passedSemester2; 
}

You can assume my tables have the a the following structure.

Teacher and Student has a bidirectional one to many relationship. Student table manages the foreign key .

I need to find out the Teachers whose students all passed semester1 and semester2. Actually I also need to search :

all failed to pass both semester1 and semester2 , all passed semester1 but failed to pass semester2 , all failed to pass semester1 but passed semester2 .

You could write any one of this queries , others should be no big differences.

In order to not cause other misunderstandings , I abstract my real problem into this simple one. I need join the two tables to do other complex queries , so it's not so easy as just to query the students table.

Thanks !

+1  A: 

In SQL, to find the teachers whose students all passed both semesters:

SELECT teacher_id
FROM student
GROUP BY teacher_id
HAVING MIN(passed_semester_1) AND MIN(passed_semester_2)

Results:

1
4

To find the teachers whose students all passed semester 1, but not all passed semester 2:

SELECT teacher_id
FROM student
GROUP BY teacher_id
HAVING MIN(passed_semester_1) AND NOT MIN(passed_semester_2)

Results:

2

Update join demonstration:

SELECT T2.*
FROM (
    SELECT teacher_id
    FROM student
    GROUP BY teacher_id
    HAVING MIN(passed_semester_1) AND MIN(passed_semester_2)
) AS T1
JOIN teacher AS T2 ON T1.teacher_id = T2.teacher_id

Using this table structure and test data:

CREATE TABLE student (student_id INT NOT NULL, teacher_id INT NOT NULL, passed_semester_1 INT NOT NULL, passed_semester_2 INT NOT NULL);
INSERT INTO student (student_id, teacher_id, passed_semester_1, passed_semester_2) VALUES
(1, 1, 1, 1),
(2, 1, 1, 1),
(3, 1, 1, 1),
(4, 2, 1, 1),
(5, 2, 1, 0),
(6, 2, 1, 1),
(7, 3, 0, 1),
(8, 3, 1, 1),
(9, 4, 1, 1);
Mark Byers
Actually I abstract my problems into this simple question . I need to join tables to do other things . Is this possible within join tables ?
ZZcat
Yes, you can join, for example to get the teacher's name.
Mark Byers
thanks Mark , I will try your suggestions .
ZZcat
Mark , if I use group by , How can I get projection of Teacher entity ? If I have ten fields in Teacher table , I can't select them all out if I have group by clause , the projection fields should be either in the group by clause or in an aggregate function .
ZZcat
@Tony: I've added an example of how to join to the results of a group by. I haven't tested it, but it hopefully demonstrates the principle.
Mark Byers