我正在尝试创建一个表,其中包含应该从另一个表继承值的列,但问题是这些值不是唯一的(不是另一个表的主键)。我怎样才能做到这一点?
我试图将其设置为外键,但无法完成,因为该值不是主键。
我想要从另一个表 (tblPartsServices) 继承的表 tblOrderCharges 中的 fldDiscountPercent 和 fldChargeType。我将如何实现这一目标?
CREATE TABLE tblPartsServices(
fldPartServiceId VARCHAR2(10) NOT NULL,
fldPartServiceDescription VARCHAR2(255),
fldPartServiceType CHAR(1) NOT NULL, -- P for Part, S for Service, O for Other
fldPartServiceAmount NUMBER(8,2) NOT NULL,
fldDiscountPercent NUMBER(2) ,
fldStatus CHAR(1) NOT NULL, -- A for Active, I for Inactive
CONSTRAINT PartService_pk PRIMARY KEY (fldPartServiceId)
);
CREATE TABLE tblOrderCharges(
fldChargeId NUMBER(10) NOT NULL,
fldChargeReference VARCHAR2(10) NOT NULL, -- Part number or service number (Could be inherited from PartsServices table)
fldChargeCode VARCHAR2(10) , -- Part number or service number (Could be inherited from PartsServices table)
fldChargeType CHAR(1), -- Type: P for Part, S for Service, O for Other (Could be inherited from PartsServices table)
fldChargeAmount NUMBER(18, 2) , -- Part or Service Amount (Could be inherited from PartsServices table)
fldDiscountPercent NUMBER(2), -- Part or Service Discount (Could be inherited from PartsServices table)
fldRemarks VARCHAR2(40),
fldStatus CHAR(1) NOT NULL, -- A for Active, I for Inactive
fldOrderId VARCHAR2(10) NOT NULL,
fldTechnicianId VARCHAR2(10), -- Null if no technician has been assigned
CONSTRAINT Charge_pk PRIMARY KEY (fldChargeId),
CONSTRAINT fk_Order FOREIGN KEY (fldOrderId) REFERENCES tblJobOrders(fldOrderId),
CONSTRAINT fk_Technician FOREIGN KEY (fldTechnicianId) REFERENCES tblTechnicians(fldTechnicianId),
CONSTRAINT fk_ChargeReference FOREIGN KEY (fldChargeReference) REFERENCES tblPartsServices(fldPartServiceId),
CONSTRAINT fk_ChargeCode FOREIGN KEY (fldChargeCode) REFERENCES tblPartsServices(fldPartServiceId),
CONSTRAINT fk_ChargeType FOREIGN KEY (fldChargeType) REFERENCES tblPartsServices(fldPartServiceType),
CONSTRAINT fk_DiscountPercent FOREIGN KEY (fldDiscountPercent) REFERENCES tblPartsServices(fldDiscountPercent)
);
最佳答案
如您所见,外键是指向另一个表的主键的链接。 This website可以帮助理解这个概念。
您可能需要考虑向表 tblOrderCharges 添加一个触发器,该触发器从其他表中选择必要的列并将选定的值放入 tblOrderCharges 中。您可以指定用于处理返回的非唯一值的过滤条件。会是这样的:
create or replace trigger myexampletrigger
before insert or update
on tblOrderCharges
for each row
DECLARE
// your variables here
BEGIN
select fldDiscountPercent,fldPartServiceType into YourVariable1,YourVariable2 from tblPartsServices where /*your criteria here*/;
:new.fldDiscountPercent := YourVariable1;
:new.fldChargeType := YourVariable2;
END;
/
关于database - 如何从另一个表继承列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158668/