0

我需要为具有以下架构的数据库创建一些查询:

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

但这样它就不会返回所有床位都无人使用的病房。

请帮我 :)

4

3 回答 3

0

就 Allocation 可以同时指定病房 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;
于 2013-05-06T11:39:30.650 回答
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
于 2013-05-06T11:44:09.237 回答
0

以下是您的问题的三种可能的解决方案。请记住,我不是为了效率。可能有一些方法可以稍微优化这些查询。我只是想给你一些想法,让你朝着正确的方向前进。

对于每个病房的无人床位:

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
于 2013-05-06T12:23:57.480 回答