我有一个网站在用户搜索主题时查询教师的个人资料。所以,例如,如果我搜索数学,我会得到所有教数学的老师 - 但不幸的是,我没有看到他们教的其他科目,因为我的条件只包括数学。我目前正在使用:
SELECT *
FROM subjects
INNER JOIN teachers_subjects ON
subjects.subject_id = teachers_subjects.subject_id
INNER JOIN users_teachers ON teachers_subjects.users_user_id = users_teachers.user_id
INNER JOIN users ON users_teachers.user_id = users.user_id
WHERE subjects.subject_en_name ='math'
这将让我老师约翰,但它只会告诉我他教数学,实际上他实际上也教科学和英语。
这两个SQL查询有效。第一个:
SELECT users.user_id
FROM subjects
INNER JOIN teachers_subjects ON
subjects.subject_id = teachers_subjects.subject_id
INNER JOIN users_teachers ON teachers_subjects.users_user_id = users_teachers.user_id
INNER JOIN users ON users_teachers.user_id = users.user_id
WHERE subjects.subject_en_name ='math'
这将返回给我一个user_id然后我可以插入:
SELECT *
FROM subjects
INNER JOIN teachers_subjects ON
subjects.subject_id = teachers_subjects.subject_id
INNER JOIN users_teachers ON teachers_subjects.users_user_id = users_teachers.user_id
INNER JOIN users ON users_teachers.user_id = users.user_id
WHERE users.user_id = 100
这给了我关于John所需的所有信息,包括他教数学,科学和英语的事实,尽管我的第一个问题只是询问数学。我想知道如何将这两个查询组合起来,所以每次搜索都不需要查询数据库两次。
UDPATE
感谢@DRapp,我认为这可能有效:
SELECT
*
from
( SELECT distinct
ts.users_user_id
from
subjects s
JOIN teachers_subjects ts
ON s.subject_ID = ts.subject_id
where
s.subject_en_name = 'math' ) qualified
JOIN users u
ON qualified.users_user_id = u.user_id
JOIN users_teachers ut
ON qualified.users_user_id = ut.user_id
JOIN teachers_subjects ts2
ON qualified.users_user_id = ts2.users_user_id
JOIN subjects s2
ON ts2.subject_id = s2.subject_id
答案 0 :(得分:2)
首先启动世界卫生组织,有资格教授相关课程(数学)
SELECT distinct
ts.users_user_id
from
subjects s
JOIN teachers_subjects ts
ON s.subject_ID = ts.subject_id
where
s.subject_en_name = 'math'
因此,这将提供一个独特的教师用户ID,即QUALIFIES ...现在,考虑您想要任何教数学或英语的老师。只需将where子句从='math'更改为IN('math','English')。它仍然只会给你一个教师的实例,即使他们教两个或只是一个或另一个。
现在,要获得你想要的其余部分。从这个有问题的主题的合格教师列表中,现在得到其余的详细信息...将其包装成另一个查询...我试图永远不会将野外卡用于许多目的,所以我只是猜测users表中的一些列名称,以获取教师信息。
SELECT
qualified.users_user_id,
u.TeacherName,
u.TeacherEmail,
ts2.OtherInformationThatMayBeAvailable,
s2.subject_id,
s2.subject_en_name,
s2.anyOtherSubjectBasedFields
from
( SELECT distinct
ts.users_user_id
from
subjects s
JOIN teachers_subjects ts
ON s.subject_ID = ts.subject_id
where
s.subject_en_name = 'math' ) qualified
JOIN users u <-- this join to get teacher name info
ON qualified.users_user_id = u.user_id
JOIN teachers_subjects ts2 <-- this to now get ALL classes per teacher qualified
ON qualified.users_user_id = ts2.users_userID
JOIN subjects s2 <-- for subjects details that the teacher TEACHES
ON ts2.subject_id = s2.subject_id
请务必通过&lt; - 在查询中的JOIN组件发表评论
来删除我的笔记因此,如果一名教师有资格获得数学,但也教授科学和英语,这将为该教师返回3条记录。如果另一个人只教数学,一个记录他们......另一个教师数学和社会研究,然后是那个人的两个。
同样,这包括您可能希望从主题表和/或教师科目中获取的所有独特主题详细信息。
如果您不关心所有具体细节,那么您按照教师的用户ID进行分组并执行“group_concat(s2.subject_en_name,',')”,它将为每位教师建立一个列表记录如“数学,科学,英语”