所有這三種付款類型都有一些共同點。他們都有一個帳號,金額,時間戳,付款類型和某種交易標識符。所有常見屬性都放在一張表中。 (有些數據類型是故意天真,因爲他們依賴於應用程序,我不知道您的應用程序。)
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