添加可以派生的字段何时正确?

时间:2017-07-19 07:51:25

标签: database-design

我想将字段entity_id添加到finance_invoice。它将加速(最低限度)读取并简化查询。

select * from finance_invoice where issuer_identity_id in (
    select id from finance_identity where entity_id = @container_entity_id
)

VS

select * from finance_invoice where container_entity_id = @container_entity_id

container_entity_id可以从issuer_identity_id派生,因为身份属于实体。

架构:

table - finance_invoice
field                 | type
id                    | int(10) unsigned
issuer_identity_id    | int(10) unsigned
recipient_identity_id | int(10) unsigned
reference_id          | int(10) unsigned
...

table - finance_identity
field                 | type
id                    | int(10) unsigned
entity_id             | int(10) unsigned
reference_id          | int(10) unsigned
... name, address fields ...

table - finance_entity
field                 | type
id                    | int(10) unsigned
type                  | int(10) unsigned
...

foreign key - invoice_issuer on finance_invoice
finance_invoice.issuer_identity_id references finance_identity.id

foreign key - invoice_recipient on finance_invoice
finance_invoice.recipient_identity_id references finance_identity.id

foreign key - identity_entity on finance_identity
finance_identity.entity_id references finance_entity.id

1 个答案:

答案 0 :(得分:0)

我明白了。

为了强制执行参照完整性,我需要将容器(创建者)实体ID添加到发票和身份中。

table - finance_invoice
field                 | type
id                    | int(10) unsigned
container_entity_id   | int(10) unsigned
reference             | varchar(255)
issuer_identity_id    | int(10) unsigned
recipient_identity_id | int(10) unsigned
invoice_date          | date
due_date              | date
currency              | char(3)
created_at            | datetime
cancelled_at          | datetime
cancelled_by          | int(10) unsigned

table - finance_identity
field                 | type
id                    | int(10) unsigned
container_entity_id   | int(10) unsigned
reference             | varchar(255)
entity_id             | int(10) unsigned
... name, address fields ...


foreign key - invoice_issuer on finance_invoice
(issuer_identity_id, container_entity_id) references (id, container_entity_id)

这也解决了从两个表中获取记录的问题,我可以使用实体id来获取身份或发票,我也不需要加入引用,而finance_reference表只是从现在开始的验证表上。