我有一个表学生,其列有rollNumber,majorSubject,minorSubject,fullName。
现在给出一个rollNumber如何查找具有相同majorSubject的所有学生,minorSubject作为具有给定rollNumber的学生。
我想出了什么:
SELECT * FROM students WHERE
majorSubject IN (SELECT majorSubject FROM students WHERE rollNumber='<rollNumber>') AND
minorSubject IN (SELECT minorSubject FROM students WHERE rollNumber='<rollNumber>')
正如您所看到的,我正在运行相同的子查询两次。我相信应该有一个优化或更好的方法。
答案 0 :(得分:0)
SELECT allSt.*
FROM students allSt
join students st
-- check the same majorSubject AND the same minorSubject --
on allSt.majorSubject = st.majorSubject and allSt.minorSubject = st.minorSubject
WHERE
st.rollNumber = '<rollNumber>' AND
-- exclude student with the given rollNumber from the result set --
allSt.rollNumber <> '<rollNumber>'