charlie
charlie

Reputation: 481

SQL Query with multiple JOINS on multiple tables

I have created this query to match data against multiple tables but i feel that it has got a little complicated.

I need to select from the following tables:

using the following relationships:

leads.sequence = instructors_options.instructor_seq
leads.sequence = instructor_calendar.instructor_seq

and the following filters MUST match:

Can someone please help me update my query to ensure I have done it correctly

Thank you!

Upvotes: 0

Views: 39

Answers (1)

Thorsten Kettner
Thorsten Kettner

Reputation: 94859

You are looking for certain calendar entries. So select from that table.

One of the conditions is that the related instructor sequence has all of four certain options. So aggregate the options per instructor sequence and keep those who match all criteria. Use an IN clause to get the calendar entries for these instructor sequences.

select 
  instructor_seq,
  date, 
  start_time, 
  end_time
from instructor_calendar 
where pupil_name = 'AVAILABLE' 
and date >= '2017-01-01' 
and date <= '2017-05-31'
and instructor_seq in
(
  select instructor_seq
  from instructors_options
  group by instructor_seq
  having sum(option_name = 'pupil_cap'     and value > 0)   > 0
     and sum(option_name = 'car_type'      and value = 123) > 0
     and sum(option_name = 'areas_covered' and value = 456) > 0
     and sum(option_name = 'diary_updates' and value = 1)   > 0
);

The HAVING clause makes use of MySQL's true = 1, false = 0 by the way.

Upvotes: 2

Related Questions