2013-05-06 80 views
0

我需要使用下面的模式創建一個數據庫中的幾個疑問:幾個SQL查詢,我無法弄清楚如何寫

Patient(**pid**,pname,address,phone) 
Ward(**wid**, wname) // wid=Ward id, 
Bed(**wid,bid**) // bid=Bed id 
Appointment(**apid**,date,result,pid,cid) // cid=Consultant id, pid=Patient id 
Consultant(**cid**,cname,clinId,phone) // clinId=Clinic ID 
Allocation(**apid**,pid,wid,bid,date,ex_leave,act_leave) //ex=expected, act=actual 

的查詢是:

  1. 查找如何每個病房都有許多空置的病牀。
  2. 找到其中它的分配是2013年3月期間,每天做
  3. 返回那些誰執行最任命誰導致 分配在骨科病房的顧問細節病房。

我試圖創建使用視圖像這樣的第一個:

create view hospital.occupied_beds as 
select A.wid,count(*) as o_beds 
from hospital.allocation A,hospital.bed B 
where A.wid=B.wid and A.bid=B.bid and A.act_leave is null 
group by A.wid; 

create view hospital.all_beds as 
select C.wid,count(*) as all_beds 
from hospital.bed C 
group by C.wid; 

select distinct A.wid,all_beds-o_beds as uo_beds 
from hospital.occupied_beds A, hospital.all_beds B 

但這種方式不返回,其中所有的牀都是空閒的病房。

請幫我:)

回答

0

這裏是你的問題的三種可能的解決方案。請記住,我沒有追求效率。有可能有一些方法來優化這些查詢。我只是想給你一些想法,讓你朝正確的方向前進。

對於每個病房Unoccipied牀:

select w.wname, bc.total - IFNULL(ob.occupied,0) as unoccupied 
from Ward w, 
(select wid, count(bid) as total from Bed group by wid) bc 
left join (select wid, count(wid) as occupied from Allocation where act_leave is null group by wid) ob 
on bc.wid = ob.wid 
where w.wid = bc.wid 

對於分配每天病房2013年3月

select w.wid, w.wname, count(distinct(a.date)) as acount 
from Ward w, Allocation a 
where a.date >= '2013-03-01' 
and a.date <= '2013-03-31' 
and w.wid = a.wid 
group by w.wid 
having acount = 31 

顧問與按降序排列最鄰任用(上最頂端的分配名單)

select c.cid, c.cname, count(a.apid) as apptcount 
from Consultant c, Appointment p, Allocation a, Ward w 
where c.cid = p.cid 
and p.apid = a.apid 
and a.wid = w.wid 
and w.wname = 'Orthopedic' 
group by c.cid 
order by apptcount desc 
+0

謝謝!第二個和第三個查詢是完美的。第一個不能正常工作,我會嘗試修改它。 – Berlyne 2013-05-06 13:48:11

+0

我修改了上面的查詢。讓我知道它現在是否有效。再次感謝 – cmbaxter 2013-05-06 14:12:20

+0

,這是完美的! – Berlyne 2013-05-06 15:10:05

0

這似乎有點標準化很差,所用的措詞分配可以同時指定病房ID和牀ID。牀ID是可空的,例如病人還沒有分配牀?

在任何情況下,我認爲你需要外部連接。我沒有的MySQL提供的複印件的權利,但我相信你可以這樣做:

create view hospital.unoccupied_beds as 
select B.wid,count(*) as o_beds 
from hospital.allocation A right join hospital.bed B on A.wid=B.wid and A.bid=B.bid and A.act_leave is null 
where A.apid is null 
group by B.wid; 
0

也許是這樣的: 你只需要計算豆蔻位:

Select Sub1.v1, Sub1.c1 as all, Sub2.c2 as free FROM 
(SELECT wid.bed as v1,count(bid.bed) as c1 FROM bed, ward WHERE wid.ward = wid.bed 
GROUP BY wid.bed) Sub1 
LEFT JOIN 
(SELECT wid.bed as v2,count(bid.bed) as c2 FROM bed, ward, allocation WHERE 
wid.ward = wid.bed AND wid.bed = wid.allocation 
AND bid.bed = bid.allocation AND act_leave.allocation IS NULL GROUP BY wid.bed) Sub2 
ON Sub1.v1 = Sub2.v2