我有这样的事情:
表:
ct_lectures [id, l_id,name,position]
ct_teachers_lectures [id, t_id, l_id]
ct_teachers [id, name, surname, position]
ct_teachers_languages [id, t_id, lang_id]
首先,我列出所有讲座,然后我尝试找到与这些讲座相关并讲特定语言的老师:
SELECT DISTINCT ct_teachers.* FROM ct_teachers_lectures, ct_teachers, ct_teachers_languages WHERE (
(ct_teachers_lectures.l_id = 27 AND ct_teachers.id = ct_teachers_lectures.t_id AND ct_teachers_languages.t_id = ct_teachers_lectures.t_id) OR
(ct_teachers_lectures.l_id = 67 AND ct_teachers.id = ct_teachers_lectures.t_id AND ct_teachers_languages.t_id = ct_teachers_lectures.t_id) OR
(ct_teachers_lectures.l_id = 133 AND ct_teachers.id = ct_teachers_lectures.t_id AND ct_teachers_languages.t_id = ct_teachers_lectures.t_id) OR
(ct_teachers_lectures.l_id = 262 AND ct_teachers.id = ct_teachers_lectures.t_id AND ct_teachers_languages.t_id = ct_teachers_lectures.t_id)
ORDER BY ct_teachers.id DESC LIMIT 30
甚至可以有15个讲座(上面的例子是4个)我想要搜索,所以会有15次这样的行:
(ct_teachers_lectures.l_id = **ID** AND ct_teachers.id = ct_teachers_lectures.t_id AND ct_teachers_languages.t_id = ct_teachers_lectures.t_id) OR
有没有更好的方法从数据库中获取这些教师而不是进行大查询?或者那些查询那么大是正常的吗?
答案 0 :(得分:2)
SELECT DISTINCT
ct_t.*
FROM
ct_teachers ct_t
INNER JOIN ct_teachers_lectures ct_tlect
ON ct_tlect.t_id = ct_t.id
INNER JOIN ct_teachers_languages
ON ct_tlang.t_id = ct_tlect.t_id
WHERE
ct_tlect.l_id = 27
OR ct_tlect.l_id = 67
OR ct_tlect.l_id = 133
OR ct_tlect.l_id = 262
ORDER BY
ct_t.id DESC
LIMIT 30;
答案 1 :(得分:0)
如果没有专门查看JOIN,可以选择使用UNION ALL
代替OR
的多个查询。