SQL查询从三个不同的表中提取数据

时间:2015-03-23 21:09:06

标签: sql oracle

我必须创建一个SQL查询,列出按名字,名字命名的'麻雀'翼中的所有护士。

但是,我需要从Nurse表中提取Nurse_name和Nurse_surname,该表通过外键Sister_ID链接到另一个名为Sister的表,然后将该表链接到另一个名为Wing的表,该表具有外键Sister_ID。

护士由姐姐管理,姐姐管理翼。

有人可以帮我解决这个问题吗?事实上,我只能从护士和姐妹桌上获取数据。

3 个答案:

答案 0 :(得分:1)

由于您似乎意识到应该使用inner join连接表(但显然不是连接需要通过相关列),您应该应用该知识来连接所需的所有表回答问题。

如果从最终结果开始并向后工作,则首先选择所需的列:

select Nurse.Nurse_name, Nurse.Nurse_surname

然后因为它们属于Nurse表,所以你在from子句中使用它作为源

from Nurse

要获得Wing你需要连接Sister表,但要连接那个和Nurse你首先需要在共享属性上加入SisterNurse表

join SisterNurse on Nurse.Nurse_ID = SisterNurse.Nurse_ID

现在您可以在与SisterNurse共享的属性

上加入Sister
join Sister on Sister.Sister_ID = SisterNurse.Sister_Id

最后你可以加入Wing

join Wing on Wing.sister_ID = Sister.Sister_ID

将Wings限制为一个名字' Sparrow'

where Wing.Wing_Name = 'Sparrow'

并订购数据

order by Nurse.Nurse_surname, Nurse.Nurse_name

把它们放在一起然后得到:

select Nurse.Nurse_name, Nurse.Nurse_surname
from Nurse
join SisterNurse on Nurse.Nurse_ID = SisterNurse.Nurse_ID
join Sister on Sister.Sister_ID = SisterNurse.Sister_Id
join Wing on Wing.sister_ID = Sister.Sister_ID
where Wing.Wing_Name = 'Sparrow'
order by Nurse.Nurse_surname, Nurse.Nurse_name

答案 1 :(得分:0)

您没有提供有关所涉及架构的大量信息,但这可能会有所帮助:

select
  n.Nurse_name
, n.Nurse_surname
, w.Wing_name
, managing_nurse.Nurse_name
, managing_nurse.surname
from
  Nurse n
  join Sister s on n.Sister_ID=n.Sister_ID
  join Wing w on s.Sister_ID=w.Sister_ID
  join Nurse managing_nurse on w.Nurse_Manager_ID=managing_nurse.Sister_ID

答案 2 :(得分:-1)

一种简单的方法是使用' union':

select * from (
select nurse_name, nurse_surname, 'nurse' as nurse_type from nurse_table
   union 
select nurse_name, nurse_surname, 'sister' as nurse_type from syster join nurse_table on nurse_table.syster_id = syster.syster_id
   union 
select nurse_name, nurse_surname, 'wing' as nurse_type from wing join syster on wing.syster_id = syster.syster_id join nurse_table on nurse_table.syster_id =  syster.syster_id )
order by nurse_surname, nurse_name

希望这对你有帮助!

P.S。 我假设syster和wing表有nurse_name和nurse_surname字段。 如果不是,则必须为所有选定的列提供相同的别名