Search code examples
sqljoininner-join

join 3 tables in a view


A table contains information for Students who are applying to live on this college campus. Another table lists the Hall Preferences (3 of them) for each Student.

I INNER JOIN the tables with their information and preferences:

 John Doe | 923423 | Incoming Student | 005

005 is the HallID.

Each of these preferences is an ID Number that has a corresponding Hall Name in a third table that contains a HallID and HallName.

Desired result:

 John Doe | 923423 | Incoming Student | Foley Hall

Foley Hall is instead of 005.

I have:

SELECT
  s.StudentID, s.FName, 
  s.LName, s.Gender, s.BirthDate, s.Email, 
  r.HallPref1, r.HallPref2, r.HallPref3
FROM
  dbo.StudentSignUp AS s 
  INNER JOIN RoomSignUp.dbo.Incoming_Applications_Current AS r 
    ON s.StudentID = r.StudentID 
  INNER JOIN HallData.dbo.Halls AS h 
    ON r.HallPref1 = h.HallID

Solution

  • You can do the following (I guessed on table fields,etc)

    SELECT s.studentname
        , s.studentid
        , s.studentdesc
        , h.hallname
    FROM students s
    INNER JOIN hallprefs hp
        on s.studentid = hp.studentid
    INNER JOIN halls h
        on hp.hallid = h.hallid
    

    Based on your request for multiple halls you could do it this way. You just join on your Hall table multiple times for each room pref id:

    SELECT     s.StudentID
        , s.FName
        , s.LName
        , s.Gender
        , s.BirthDate
        , s.Email
        , r.HallPref1
        , h1.hallName as Pref1HallName
        , r.HallPref2 
        , h2.hallName as Pref2HallName
        , r.HallPref3
        , h3.hallName as Pref3HallName
    FROM  dbo.StudentSignUp AS s 
    INNER JOIN RoomSignUp.dbo.Incoming_Applications_Current AS r 
        ON s.StudentID = r.StudentID 
    INNER JOIN HallData.dbo.Halls AS h1 
        ON r.HallPref1 = h1.HallID
    INNER JOIN HallData.dbo.Halls AS h2
        ON r.HallPref2 = h2.HallID
    INNER JOIN HallData.dbo.Halls AS h3
        ON r.HallPref3 = h3.HallID