Finding rows for a specified date range
It seems that the following code solves my problem:

SELECT DISTINCT groupid
FROM pupilgroupteacher x
WHERE teacherid=@teacher AND startdate&lt;@month+INTERVAL 1 MONTH AND
NOT EXISTS(
SELECT *
FROM pupilgroupteacher
WHERE groupid=x.groupid AND teacherid!=@teacher AND startdate&gt;x.startdate AND startdate&lt;@month
)

(Here @month is the date of the first day of the specified month and @teacher is the teacher ID.)

But:


is this code error-free? Please help to check it.
can it be optimized to use fewer server resources?