您可以将外键添加到患者表中,如下所示。抱歉,此查询在 MYSQL 中。我注意到你需要 Oracle。然而逻辑是相似的:) 语法需要改变。
Create table ward(
Wno varchar(15) Not null Primary Key,
Name varchar(20) Not Null,
Number_of_beds integer Not Null
);
和一张给病人的桌子:
Create table patient(
Pid varchar(15) Primary Key,
Name varchar(20) Not Null,
Address varchar(50) Not Null,
Date_of_birth date Not Null,
WardNo varchar(15),
foreign key (wardno) references ward (wno) ' -- adds the foreign key relation
);
为了检查病房是否已满,您可以使用insert
或update trigger
免费床位数可通过以下查询获得:
SELECT p.wardno, (w.number_of_beds - count(pid)) as freebeds
from patient as p
left join ward as w
on p.wardno = w.wno
group by wardno
现在我们创建一个触发器来检查是否有任何患者进入病房,其中 freebed count = 0。
更新到 Oracle 版本
CREATE OR REPLACE TRIGGER FreeBedsWardTrigger
BEFORE UPDATE OR INSERT
ON patient
FOR EACH ROW
DECLARE
max_beds INTEGER; -- max number of beds for the ward
used_beds INTEGER; -- used beds for the ward
BEGIN
SELECT COUNT (pid)
INTO used_beds
FROM patient
WHERE wardno = :NEW.wardno;
SELECT number_of_beds
INTO max_beds
FROM ward
WHERE wno = :NEW.wardno;
IF (max_beds - used_beds) > 0
THEN
RETURN;
ELSE
RAISE_APPLICATION_ERROR (-100100,
'No more beds available in this ward.');
END IF;
END;