我看过很多帖子,但没有得到我的答案我有一张有结构的表格

 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             |

我要提取一个特定级别的1、2或更多科目的导师的导师id(科目的数量取决于用户对科目的选择,可以有,但级别对于特定查询是唯一的)
我在其他帖子的帮助下做了一个查询,但是速度很慢,如果科目数超过两个,情况会更糟,因为我有10000个导师记录,我的查询是:
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

建议:SELECTING with multiple WHERE conditions on same column
这个问题和我的问题的不同之处在于,我想要两门课都教的老师。
更新:是的,主要关注的是性能,对于两个主题,这个查询运行得很好,但是对于两个以上的主题,mysql服务器会一直在处理。索引subject_level_id中有将近13000条记录,下面的查询返回大约6500个结果。
正如Jakub Sacha所要求的,这些是
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

最佳答案

您的查询似乎没有执行您描述的操作。连接应该在tutor_id上,而不是在level_id_fk上。
只有当DISTINCT组合不唯一时,才需要(level_id_fk, subject_id_fk, tutor_id)

SELECT
    -- DISTINCT
   a.tutor_id
FROM
   tutor_preferred_level_subject AS a
INNER JOIN
   tutor_preferred_level_subject AS b
       ON a.tutor_id = b.tutor_id
WHERE
   a.subject_id_fk = 1 AND
   a.level_id_fk = 3 AND
   b.subject_id_fk = 10 AND
   b.level_id_fk = 3 ;

此外,为了提高效率,您应该在(level_id_fk, subject_id_fk, tutor_id)上添加一个(唯一的)索引:
ALTER TABLE tutor_preferred_level_subject
  ADD INDEX level_subject_tutor_IDX
    (level_id_fk, subject_id_fk, tutor_id) ;

关于php - 在同一列上具有多个WHERE条件的选择必须同时存在,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14134631/

10-12 15:27