我试图在视图中连接3个表;情况是这样的:

我有一张表格,上面有申请在这所大学校园居住的学生的信息。我有另一个表,列出了每个学生的大厅偏好(其中3个)。但是每个参数都只是一个ID Number,并且ID Number在第三个表中有一个对应的Hall Name(没有设计这个数据库…)。

基本上,我在表中有INNER JOIN和它们的首选项,以及它们的信息,结果是这样的。

 John Doe | 923423 | Incoming Student | 005

005是HallID。所以现在我想把这个HallID匹配到第三个表,这个表包含HallID和HallName。

所以,我希望结果是这样的。

 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

当前回答

您可以执行以下操作(我猜是在表字段等上)

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

根据你对多个大厅的要求,你可以这样做。您只需为每个房间加入您的大厅桌子多次:

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

其他回答

SELECT column_Name1,column_name2,......
  From tbl_name1,tbl_name2,tbl_name3
  where tbl_name1.column_name = tbl_name2.column_name 
  and tbl_name2.column_name = tbl_name3.column_name
SELECT table1.col,table2.col,table3.col 
FROM table1 
INNER JOIN 
(table2 INNER JOIN table3 
ON table3.id=table2.id) 
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE
SELECT * 
FROM 
    PersonAddress a, 
    Person b,
    PersonAdmin c
WHERE a.addressid LIKE '97%' 
    AND b.lastname LIKE 'test%'
    AND b.genderid IS NOT NULL
    AND a.partyid = c.partyid 
    AND b.partyid = c.partyid;
select products.product_id, product_name, price, created_at, image_name, categories.category_id, category_name,brands.brand_id, brand_name 
FROM products INNER JOIN categories USING (category_id) INNER JOIN brands USING(brand_id)

这是对id相同的连接3表的正确查询

select a.empname,a.empsalary,b.workstatus,b.bonus,c.dateofbirth from employee a, Report b,birth c where a.empid=b.empid and a.empid=c.empid and b.empid='103';

员工第一表。 报告第二表。 出生第三表