我正在尝试创建一个包含应该从另一个表继承值的列的表,但问题是这些值不是唯一的(不是来自另一个表的主键)。我怎么能做到这一点?
我试图将其设置为外键,但由于该值不是主键,因此无法完成。
我希望从另一个表(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)
);
答案 0 :(得分:3)
正如您所看到的,外键是指向另一个表的主键的链接。 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;
/