I have seen many posts but didn't get my answer i have a table with structure
subject_level_id | tutor_id | level_id_fk | subject_id_fk |
118 | 99 | 4 | 1 |
119 | 99 | 3 | 2 |
120 | 99 | 3 | 3 |
121 |100 | 3 | 1 |
122 |100 | 4 | 2 |
I want to extract tutor id's of tutors which teach 1, 2 or more subjects of a particular level( number of subjects depend upon user selection of subjects there can be but level will be unique for aparticular query)
I have worked out a query with help from other posts but it is very slow and gets worse if number of subjects are more than two because I have 10,000 records of tutors my query is:
select distinct
a.tutor_id
from
tutor_preferred_level_subject as a
inner join
tutor_preferred_level_subject as b
on a.level_id_fk = b.level_id_fk
where
a.subject_id_fk = 1 and
b.subject_id_fk = 10 and
a.level_id_fk = 3
Suggestion: SELECTING with multiple WHERE conditions on same column
The difference in this question and mine is that I want the tutors who teach exactly both the subjects.
update: yes main concern is performance, this query is working fine for two subjects but for more than two subjects mysql server keeps on processing forever. The index is subject_level_id
and there are almost 13000 records in it and the below query returns around 6500 results.
as Jakub Sacha demanded these are the results of
EXPLAIN select distinct
a.tutor_id
from
tutor_preferred_level_subject as a
inner join
tutor_preferred_level_subject as b
on a.level_id_fk = b.level_id_fk
where
a.subject_id_fk = 1 and
b.subject_id_fk = 10 and
a.level_id_fk = 3
id select_type table type possible_keys key key_len ref|
1 SIMPLE a ALL NULL NULL NULL NULL
1 SIMPLE b ALL NULL NULL NULL NULL
rows Extra
12733 Using where; Using temporary
12733 Using where; Distinct