简体   繁体   中英

How to get all the rows from MySQL table which have same values for multiple columns?

I have a table students with columns rollNumber, majorSubject, minorSubject, fullName.

Now given a rollNumber how to find all the students who have same majorSubject, minorSubject as the student with the given rollNumber.

What I came up with:

SELECT * FROM students WHERE
majorSubject IN (SELECT majorSubject FROM students WHERE rollNumber='<rollNumber>') AND
minorSubject IN (SELECT minorSubject FROM students WHERE rollNumber='<rollNumber>')

As you can see I am running the same subquery twice. I am sure there should be an optimized or a better to do this.

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>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM