Probuje pobrac rekord o najmniejszym czasie z danej tabeli, niestety dostaje złe wyniki:(

TABELA course
id id_line
1 1
3 1
2 2

TABELA calendar
id_course date id_schedule
1 2008-09-11 1
2 2008-09-11 2
3 2008-09-11 3


TABELA schedule
id id_stop time
1 1 09:40:00
2 1 11:00:00
3 1 08:00:00


  1. SELECT MIN( schedule.time ) AS min, schedule.id
  2. FROM schedule INNER JOIN calendar ON calendar.id_schedule = schedule.id
  3. INNER JOIN course ON calendar.id_course = course.id
  4. WHERE schedule.time > "07:35:04" AND calendar.date = "2008-09-11" AND schedule.id_stop =1
  5. GROUP BY course.id_line


Po wykonaniu tego zapytania dostaje taki wynik:
min id
08:00:00 1 <- (ID dla tego rekordu powinno wynosic 3)
11:00:00 2

Po wielu godzinach prób znalazłem rozwiązanie. Z pomocą jak zwykle przyszedł manual MySQL.

Poniższy tekst tłumaczy czemu MySQL zwracał mi wyniki:
If the columns you omit from the GROUP BY part are not constant in the group. The server is free to return any value from the group, so the results are indeterminate unless all values are the same.

Problem rozwiązałem po analizie tych przykładów:
The Rows Holding the Group-wise Maximum of a Certain Field

Rozwiązanie:
  1. SELECT s1.time, s1.id FROM schedule AS s1
  2. INNER JOIN ( SELECT MIN( schedule.time ) AS min FROM schedule INNER JOIN calendar ON calendar.id_schedule = schedule.id
  3. INNER JOIN course ON calendar.id_course = course.id
  4. WHERE schedule.time > "07:35:04" AND calendar.date = "2008-09-11" AND schedule.id_stop =1
  5. GROUP BY course.id_line) AS s2 ON s1.time = s2.min JOIN calendar ON calendar.id_schedule = s1.id
  6. JOIN course ON calendar.id_course = course.id
  7. WHERE s1.id_stop =1