Here,关于这个问题有一个很好的答案,但我没有找到关于下一步的明确例子,例如查询(选择)。
我将描述一个例子,我想知道我是否正确这样做:
我们有一个关于付款的基类:
Payments( code_payment (PK), description )
然后,我们有3个子类(3种不同类型的继承付款):
Cash( code_payment (FK) )
CreditCard( creditcard_account , code_payment(FK) )
PromissoryNote( pay_date , code_payment(FK) )
例如:表示插入语句,优先,插入付款表格和第二,具体取决于付款类型(我认为在代码中使用if / else子句来分隔付款类型并执行正确的“插入语句”),插入所属的地方。 select语句会发生什么?
想象一下,我想知道具体文档的付款类型,假设我有一个名为文档的表格,它与付款表格相关联(因此文档表格有一个外键付款(code_payment))。
首先,我要做的是通过在“文档和付款”表(基本上是内部联接)上进行查询来获得付款的“描述”,然后取决于结果< / strong>(现金,信用卡或本票)对所属的表格进行查询。
这是我想做的吗?我正确的方式吗?也许它可以工作,但它看起来有点......你知道..没有优雅的解决方案。我有点困惑。
提前致谢。
答案 0 :(得分:1)
通常,您将为每个“子类”构建一个可更新视图。每个视图都将“基类”表与“子类”表连接起来。
应用程序代码使用视图,而不是基表。
由于付款类型是独家付款 - 单笔付款不能同时是现金和信用卡 - 您需要使用重叠约束。
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)
);
信用卡付款和承兑票据付款的表格类似。
payments (code_payment, payment_type)
上的唯一约束允许这些列成为外键约束的目标。表“cash_payments”中的检查约束和外键约束保证“cash_payments”中的行始终与付款表中的 cash 行匹配;他们永远不会匹配任何其他类型的行。 “cash_payments”中的唯一约束允许命名列成为进一步外键约束的目标,就像“付款”中的唯一约束一样。
想象一下,我想知道具有特定文档的付款类型,假设我有一个名为Document的表,它与Payments表相关联(因此Document表有一个外键付款*(code_payment)*)。 / p>
文档可以与引用
的外键的付款相关如果“文档”表引用了这对列,您就知道付款类型是什么,因此您知道需要加入哪些表。