约束问题,一列中的值必须以另一列中的值为前缀(不同表)

问题描述 投票:-1回答:1

Prescription表:

Prescription ID (PK)
Appointment ID FK
Quantity
Drug Name
Patient Name
Physician Name

约会]表:

Appointment ID (PK)
Center(FK)
Patient ID(FK)

每个处方(ID)由约会ID标识,后跟序列号(例如2003919_1、2003919_2)

我已经建立了关系,但是如何建立约束?

[处方表:处方ID(PK)约会ID FK数量药物名称患者姓名医师姓名约会表:约会ID(PK)中心(FK)患者ID(FK)每个处方(ID)为...]]] >>

要在约会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.

然后插入了一个处方-您让触发器填充pipulation_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
mysql sql database oracle relational
1个回答
0
投票

要在约会ID字段上创建外键约束,您可以这样做:

© www.soinside.com 2019 - 2024. All rights reserved.