Ruby on Rails Wednesday, January 5, 2011

Have you considered an inner and outer join to the courses_times
table?

select distinct courses.*
from courses
inner join course_times monday_courses on courses.id =
monday_courses.course_id and monday_courses.time_id = 1
left outer join course_times non_monday_courses on courses.id =
non_monday_courses.course_id and non_monday_courses.time_id <> 1
where non_monday_courses.id is null

On Jan 5, 12:38 pm, Fernando Leandro <fernandoleandro1...@gmail.com>
wrote:
> Hello guys,
>
> I have a problem with how to do a sql query.
>
> I have 3 tables: courses, times and courses_times
>
> So for example, if i have the following data:
>
>  Courses                   courses_times                   Times
> id  |   name               course_id | time_id            id   |  day
>
> 1   | Math                            1  |  1                     1   |
> Monday
> 2   | Chimestry                     1  |  2                     2   |
> Wednesday
> 3   | History                         1  |  3                     3   |
> Friday
> 4   | Geografy                      2  |  1
>                                           2  |  2
>                                           3  |  1
>
> So, now, i want to make a query that returns to me only the courses that are
> ministred on Monday,
> but just ONLY Monday. For example, if a course is ministred Monday and
> Wednesday i dont want.
> In this example, i would like that my query returns just History, because is
> the only course
> that is just on Monday.
>
> SELECT courses.*
> FROM courses
> INNER JOIN courses_times ON courses_times.course_id = courses.id
> INNER JOIN times ON courses_times.time_id = times.id
> AND times.day = 'Monday'
>
> When i use a query like above, for example, it returns to me all the courses
> that have association with Monday,
> it returns Math, Chimestry and History, and i would like to receive just
> History
>
> I know that this question is not about rails but i need to solve this
> problem to continue my rails app,
> and i would appreciate if someone could help me..
>
> Does anyone have a solution for this?
>
> Thanks a lot
>
> Fernando

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment