0

在这里,关于这个问题有一个很好的答案,但我没有找到关于下一步的明确示例,例如查询(选择)。

我将描述一个例子,我想知道我这样做是否正确:

我们有一个关于付款的基类:

Payments( code_payment (PK), description )

然后,我们有 3 个子类(3 种不同类型的继承支付):

Cash( code_payment (FK) )
CreditCard( creditcard_account , code_payment(FK) )
PromissoryNote( pay_date , code_payment(FK) )

例如:对于插入语句,首先,在 Payments 表上插入,其次,根据付款类型(我认为在代码中您使用 if/else 子句来分隔付款类型并执行正确的“插入语句”),插入 where属于。select 语句会发生什么?

想象一下,假设我有一个名为Document的表,它与Payments 表连接(因此 Document 表具有 Payments 的外键(code_payment)),我想知道哪种类型的付款具有特定的文档。

首先我应该做的是通过查询 Document and Payments 表(基本上是一个内部连接)来获取付款的“描述”,然后根据结果(现金、信用卡或本票)进行查询属于的表。

这是我应该做的吗?我走对了吗?也许它可以工作,但它看起来有点......你知道......没有优雅的解决方案。我对此有点困惑。

提前致谢。

4

1 回答 1

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) 
);

信用卡支付表和本票支付表是相似的。

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.

于 2013-05-15T12:17:48.467 回答