2014-10-10 30 views
-1

處方表 處方ID(PK) 預約ID FK 數量 藥品名稱 患者姓名 醫師姓名約束問題,從一列值需要與另一個(不同的表)的值

可以preffixed

預約表 預約ID(PK) 中心(FK) 病人ID(FK)

「每個處方(ID)由約定ID和序列號(例如,2003919_1,2003919_2)標識」

我已經創建了關係,但是如何建立約束?

+1

請編輯您的問題,並添加表(S)和您定義的列以及可能存在的約束等信息。謝謝。 – 2014-10-10 02:53:18

回答

0

要創建約會id字段外鍵約束,你可以這樣做:

ALTER TABLE prescription 
ADD CONSTRAINT fk_appointment 
FOREIGN KEY (appointment_id) 
REFERENCES appointment(appointment_id); 

基本上意味着你創建必須在預約表中存在的每個處方記錄預約ID值 - 這就是你想做什麼?

對 - 對不起,暫時沒有回覆你。

我把處方上表中,基本上會計算已存在的新處方預約ID的行數插入扳機之前,增加了一個,然後使用,作爲處方ID:

CREATE OR REPLACE TRIGGER tr_prescription_appointment_id 
BEFORE INSERT ON prescription 
FOR EACH ROW 
BEGIN 


select to_char(:new.appointment_id) || '_' || to_char(count(prescription_id) + 1) 
into :new.prescription_id 
from prescription 
where appointment_id = :new.appointment_id; 

EXCEPTION 
WHEN OTHERS THEN 
    raise_application_error(-20700,'Error in setting new prescription_id for appointment_id: ' || :new.appointment_id || '. Error Message: '|| sqlerrm); 

END tr_prescription_appointment_id; 
/

在我的測試我剛剛創建的兩個表的主鍵列,然後插入預約

select * from appointment 

APPOINTMENT_ID 
-------------- 
     1 
1 row selected. 

然後插入一個藥方 - 你讓觸發填充prescription_id列。

insert into prescription (appointment_id) values (1); 

select * from prescription; 
PRESCRIPTION_ID APPOINTMENT_ID 
--------------- -------------- 
1_1       1 
1 row selected. 

再做一次任命1

insert into prescription (appointment_id) values (1); 

PRESCRIPTION_ID APPOINTMENT_ID 
--------------- -------------- 
1_1       1 
1_2       1 

2 rows selected. 

希望,做你所需要的。

哦,因爲如果爲處方預約ID不會在約會表中存在的錯誤,這只是一個單純的外鍵約束

ALTER TABLE prescription 
ADD CONSTRAINT prescription_appointment_id_fk 
FOREIGN KEY (appointment_id) 
REFERENCES appointment (appointment_id) 
ENABLE VALIDATE 
+0

不完全是,我想檢查每個處方ID(PK)是由一個現有的約會ID加下劃線和一組數字組成。例如:如果3個處方來自約會1,則處方ID(1_1 1_2 1_3)上會有三個條目。如果下劃線左側的內容不對應有效的約會ID,我想觸發一個錯誤 – user3258494 2014-10-10 16:25:18

相關問題