SQL内部联接与3个表? [英] SQL Inner-join with 3 tables?

查看:68
本文介绍了SQL内部联接与3个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个视图中联接3个表;这是情况:

I'm trying to join 3 tables in a view; here is the situation:

我有一张桌子,其中包含正在申请住在此大学校园的学生的信息.我还有另一个表格,列出了每个学生的大厅偏好设置"(其中有3个).但是这些首选项只是一个ID号,并且ID号在第三张表中有一个对应的Hall Name(不是设计此数据库...).

I have a table that contains information of students who are applying to live on this College Campus. I have another table that lists the Hall Preferences (3 of them) for each Student. But each of these preferences are merely an ID Number, and the ID Number has a corresponding Hall Name in a third table (did not design this database...).

我的桌子上有INNER JOIN个,包括他们的偏好设置和他们的信息,结果类似于...

Pretty much, I have INNER JOIN on the table with their preferences, and their information, the result is something like...

 John Doe | 923423 | Incoming Student | 005

其中005将是HallID.所以现在我想将HallID匹配到第三张表,该表包含一个HallIDHallName.

Where 005 would be the HallID. So Now I want to match that HallID to a third table, where this table contains a HallID and HallName.

非常希望我的结果像...

So pretty much, I want my result to be like...

 John Doe | 923423 | Incoming Student | Foley Hall <---(INSTEAD OF 005)

这是我目前拥有的:

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

推荐答案

您可以执行以下操作(我猜对表格字段等)

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

根据您对多个礼堂的要求,您可以采用这种方式.您只需为每个房间的偏好ID在Hall桌子上多次加入:

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

这篇关于SQL内部联接与3个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆