如何从 MySQL table 中获取多列具有相同值的所有行?
How to get all the rows from MySQL table which have same values for multiple columns?
我有一个 table 学生,他们的列有 rollNumber、majorSubject、minorSubject、fullName。
现在给定一个 rollNumber 如何找到与具有给定 rollNumber 的学生具有相同主修科目、辅修科目的所有学生。
我想到了什么:
SELECT * FROM students WHERE
majorSubject IN (SELECT majorSubject FROM students WHERE rollNumber='<rollNumber>') AND
minorSubject IN (SELECT minorSubject FROM students WHERE rollNumber='<rollNumber>')
如您所见,我运行同一个子查询两次。我相信应该有一个优化或更好的方法来做到这一点。
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>'
我有一个 table 学生,他们的列有 rollNumber、majorSubject、minorSubject、fullName。
现在给定一个 rollNumber 如何找到与具有给定 rollNumber 的学生具有相同主修科目、辅修科目的所有学生。
我想到了什么:
SELECT * FROM students WHERE
majorSubject IN (SELECT majorSubject FROM students WHERE rollNumber='<rollNumber>') AND
minorSubject IN (SELECT minorSubject FROM students WHERE rollNumber='<rollNumber>')
如您所见,我运行同一个子查询两次。我相信应该有一个优化或更好的方法来做到这一点。
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>'