SQL连接表和显示数据

时间:2013-03-17 05:31:28

标签: sql join

我有三张桌子与医院有关,我遇到了麻烦。

http://postimage.org/image/hi2c4yrrf/

入学包含patientid,录取,出院日期和病房。
医生 doctorid,Surname,Firstname和ward 病房 wardid,名称和顾问(doctorid)

我已经能够做很多教程要求我,但我找不到任何关于如何做以下的指导或答案:

我希望找到患者不使用的医生的姓氏,并显示患者使用的姓氏。我猜是加入医生和沃德的表格并且还以某种方式承认医生530没有被任何患者使用。

然后我应该有一个AND来显示与病房表中的顾问相对应的医生的姓氏。

要查找未接受任何患者治疗的医生的详细信息,我将加入Doctor with Ward并显示不属于顾问专栏的医生的详细信息。我理解这个理论,我只是不确定如何在SQL中正确地解决它。

我欢迎任何讨论或帮助解答,因为我真的很想理解这一步。

1 个答案:

答案 0 :(得分:0)

患者未使用的医生

select distinct d.number, d.surname
from doctor d
left join ward w on w.consultant = d.number
left join admission ad on ad.ward = w.code
left join patient p on p.code = ad.patient
where p.code is null

患者使用的医生

select distinct d.number, d.surname
from doctor d
join ward w on w.consultant = d.number
join admission ad on ad.ward = w.code
join patient p on p.code = ad.patient

架构(用于测试):

select * into patient
from (
  select 'A102' [code], 'Harris' [surname], 'Lucy' [lastname] union all 
  select 'B372', 'Rossini', 'Peter' union all
  select 'B534', 'Johnson', 'Nadia' union all
  select 'B444', 'Johnson', 'Juigi' union all
  select 'S555', 'Rose', 'Jean') as p

select * into admission
from (
  select 'A102' [patient], null [admitted], NULL [discharged], 'A' [ward] union all
  select 'A102', null, NULL, 'A' union all
  select 'S555', null, NULL, 'B' union all
  select 'B444', null, NULL, 'B' union all
  select 'S555', null, NULL, 'A') as ad

select * into doctor
from (
  select 203 [number], 'Black' [surname], 'Peter' [firstname], 'A' [ward] union all
  select 574, 'Blis', 'Mavis', 'B' union all
  select 461, 'Boyne', 'Steve', 'B' union all
  select 530, 'Clark', 'Nicola', 'C' union all
  select 405, 'Mizzi', 'Nicola', 'A' union all
  select 501, 'Mount', 'Mavis', 'A') as d

select * into ward
from (
  select 'A' [code], 'Surgical' [name], 203 [consultant] union all
  select 'B', 'Paediatric', 574 union all
  select 'C', 'Medical', 530) as w