通常,您会为每个“子类”构建一个可更新视图。每个视图都会将“基类”表与“子类”表连接起来。
应用程序代码使用视图,而不是基表。
由于支付类型是专有的——单次支付不能同时是现金和信用卡——你需要使用重叠约束。
create table payments (
code_payment integer not null, -- I hope this is some kind of payment identifier.
payment_type char(2) not null
check (payment_type in ('CA', 'CC', 'PN')),
amount decimal(14, 2) not null check (amount > 0),
other_columns char(1) not null default 'X',
primary key (code_payment),
unique (code_payment, payment_type)
);
create table cash_payments (
code_payment integer not null,
payment_type char(2) not null default 'CA'
check (payment_type = 'CA'),
other_columns char(1) not null default 'X',
primary key (code_payment),
unique (code_payment, payment_type),
foreign key (code_payment, payment_type)
references payments (code_payment, payment_type)
);
信用卡支付表和本票支付表是相似的。
The unique constraint on payments (code_payment, payment_type)
lets those columns be the target for foreign key constraints. The check constraint and foreign key constraint in the table "cash_payments" guarantees that rows in "cash_payments" will always match a cash row in the payments table; they can never match any other kind of row. The unique constraint in "cash_payments" lets the named columns be the target for further foreign key constraints, just like the unique constraint in "payments" does.
Imagine that i want to know what type of payment had a specific document assuming that I have a table called Document that it is connected with Payments table ( so Document table have a foreign key to Payments *(code_payment)* ).
Documents can be related to payments with a foreign key referencing either
- the "code_payment" column, or
- the pair of columns "code_payment" and "payment_type".
If the "documents" table references the pair of columns, you know what the type of payment is, so you know which table(s) you need to join on.