所有这三种付款类型都有一些共同点。他们都有一个帐号,金额,时间戳,付款类型和某种交易标识符。所有常见属性都放在一张表中。 (有些数据类型是故意天真,因为他们依赖于应用程序,我不知道您的应用程序。)
create table payment_types (
payment_type_code char(2) primary key,
payment_type varchar(8) not null unique
);
insert into payment_types values
('Ca', 'Cash'),('Cr', 'Credit'),('Ba', 'Bank');
create table payments (
transaction_id integer primary key,
account_code varchar(5) not null, -- references accounts, not shown
amount_usd numeric(5,2) not null,
payment_type_code char(2) not null references payment_types (payment_type_code),
transaction_timestamp timestamp not null default current_timestamp,
unique (transaction_id, payment_type_code)
);
上{TRANSACTION_ID,payment_type_code}唯一性约束让SQL使用对列作为外键约束的目标。这对于保持几张表中的行不会混淆起来至关重要。
根据付款类型的不同,每种付款都有不同的属性。每笔付款只能有一种类型。
create table payment_cash (
transaction_id integer primary key,
payment_type_code char(2) not null default 'Ca' check (payment_type_code = 'Ca'),
foreign key (transaction_id, payment_type_code)
references payments (transaction_id, payment_type_code),
other_cash_columns char(1) not null
);
create table payment_credit (
transaction_id integer primary key,
payment_type_code char(2) not null default 'Cr' check (payment_type_code = 'Cr'),
foreign key (transaction_id, payment_type_code)
references payments (transaction_id, payment_type_code),
other_credit_columns char(1) not null
);
create table payment_bank (
transaction_id integer primary key,
payment_type_code char(2) not null default 'Ba' check (payment_type_code = 'Ba'),
foreign key (transaction_id, payment_type_code)
references payments (transaction_id, payment_type_code),
other_bank_columns char(1) not null
);
payment_type_code的默认值和检查约束使得例如不可能为现金支付插入信用详情。 将是可能的 - 这将是一件坏事 - 如果外键约束只使用事务ID。
作为一般规则,您不会级联更新或删除金融交易。相反,通过插入补偿事务来纠正错误。
为了使这对用户和应用程序代码更友好,创建三个可更新的视图,将付款表加入到详细信息中。如何使它们可以更新取决于你的dbms。
create view credit_payments_all as
select p.transaction_id, p.account_code, p.amount_usd,
p.payment_type_code, p.transaction_timestamp,
c.other_credit_columns
from payments p
inner join payment_credit c on c.transaction_id = p.transaction_id
-- Rules, triggers, stored procedures, functions, or whatever you need
-- to make this view updatable.
然后任何需要插入信用事务的代码都可以插入视图credit_payments_all中。
付款类型没有不同的细节。 *付款*有不同的细节。 – 2012-03-12 13:25:17