0

我正在使用 MS Visio 对数据库进行建模,模型的一部分包含事务类别 - 父表具有事务 ID、时间戳、金额和事务类型。有三个子表 - 支票、银行转账和信用卡,它们都通过 transactionId 与父表相关。

在 SQL Server 中是否有实现这种关系的特定方式,或者它只是一个概念模型,将实现留给我?如果是后者,如果表都与 transactionId 相关,为什么在父表中有一个 transactionType 列 - 只是为了缩小我的查询范围?也就是说,如果父表中的一行将“支票”指定为事务类型,我知道我只需要查询/加入支票子表吗?

我突然想到 - 这只是一个 ISA 层次结构,在这种情况下,我将创建三个不同的表,每个表都包含 ISA 父实体中标识的列?

4

2 回答 2

1

如果您想查询所有交易,例如对每种交易类型的金额求和,父表中的 transactionType 很有用:

select transactionType, sum(amount)
from transactions 
group by transactionType

如果没有该列,您仍然可以通过查询子表来做到这一点:

select 
    case when c.transactionId is not null then 'CHEQUE'
         when cc.transactionId is not null then 'CREDIT CARD'
         ...
    end
,   sum(amount)
from transactions t
left join cheque c on t.transactionId = c.transactionId
left join creditcard cc on t.transactionId = cc.transactionId
...
group by 
    case when c.transactionId is not null then 'CHEQUE'
         when cc.transactionId is not null then 'CREDIT CARD'
         ...
    end

如您所见,这要困难得多,并且需要为您添加的每种交易类型扩展查询。

于 2010-01-20T16:19:27.600 回答
1

这本质上是多表继承,尽管您可以根据需要在域中将其建模为简单的引用关系。

拥有选择器字段/属性有很多很好的理由。显而易见的是,应用程序或服务获得了有关如何加载详细信息的提示,因此它不必从每个可能的表中加载每个可能的行(当您有 20 种不同类型的事务时尝试此操作)。

另一个原因是最终用户在很多时候不一定需要知道交易的细节,但确实需要知道交易的类型。如果您正在查看来自某个财务或计费系统的 A/R 报告,大多数情况下,您需要了解的基本报告只是之前的余额、金额、后续余额和交易类型。没有这些信息,很难阅读。分类帐不一定显示每笔交易的详细信息,有些系统甚至可能根本不跟踪详细信息。

The most common alternative to this type of model is a single table with a whole bunch of nullable columns for each different transaction type. Although I personally despise this model, it's a requirement for many Object-Relational Mappers that only support single-table inheritance. That's the only other way you'd want (or not want) to model this in a database.

于 2010-01-20T16:25:10.863 回答