规范化3个数据库表

时间:2012-02-16 22:51:44

标签: database normalization database-normalization

您好我分离了3种付款方式有问题:现金,信贷,银行

每个人都有不同的细节。 详细信息是用户定义的,表示在信用卡付款中(例如:您应输入您的信用卡详细信息,银行详细信息,现金详细信息(货币等))

  1. 业务流程:用户将在a中选择其付款方式 组合框:
  2. 然后,用户将输入该付款类型的详细信息。
  3. 这是我尝试过的:

    PaymentType(PaymentType_ID(PK),PaymentTypes)

    ... ..... ...... .........

    然后我被卡住了。我不知道怎么回事。请帮我。如果你愿意回答我的解释。我不想再在这里提出同样的问题。如果我遇到类似的情况。

    ***我无法将所有这些合并到1个表中,因为它们的列不同。他们有不同的具体细节......

1 个答案:

答案 0 :(得分:0)

所有三种付款方式都有一些共同之处。它们都有帐号,金额,时间戳,付款类型和某种交易标识符。所有常见属性都放在一个表中。 (有些数据类型是故意天真的,因为它们依赖于应用程序,我不知道你的应用程序。)

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中。