Search code examples
mysqlsqlrdbms

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.


Solution

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