具有条件约束的 SQL 表设计
我有一个表格设计问题,需要一个巧妙的解决方案。
假设我有两个具有关系的表:
Contract 1---N Payment
现在,假设我有需要放入这些表中的遗留数据。但问题是,许多遗留的支付条目是跨多个合约聚合的
,因此我们实际上可以将其视为:
新:
SomethingAboveContract 1---N Contract 1---N Payment
遗留:
SomethingAboveContract 1---N Payment
现在,我可以通过在合约和支付之间创建 MN 关系来解决这个问题。
Contract 1---N ContractPayment N---1 Payment
(我可以识别与聚合付款相关的所有合同)
这对于遗留数据来说很好,但我实际上确实想在未来强制执行合同和付款之间的 1-N 关系。因此,用我非常不方便的潦草来说明,我想这样做:
即付款在哪里聚合时,ContractID 将为 NULL,否则不应为 null。换句话说,我需要找到一种方法来在 Payment 表上强制执行以下意外情况:
- 如果 PaymentID 出现在 ContractPayment 中,
- ContractID 可为空 如果 PaymentID 未出现在 ContractPayment 中,ContractID 则不可为空
我不知道如何执行此操作。
即使这是可能的,它看起来确实有点难看(遗留数据转换总是如此)。因此,如果有人有更优雅的解决方案,那就太好了。否则,任何有效的方法!
谢谢
卡尔
I have a table design problem for which I need a cunning solution.
Let's say I have two tables, with relationship:
Contract 1---N Payment
Now, let's say I have legacy data that needs to go into these tables. The problem though is that many of the legacy Payment entries are aggregated across mulitple contracts
So we could actually view this as:
New:
SomethingAboveContract 1---N Contract 1---N Payment
Legacy:
SomethingAboveContract 1---N Payment
Now, I can get around this by creating an M-N relationship between Contract and Payment.
Contract 1---N ContractPayment N---1 Payment
(it will be possible for me to identify all the contracts that are linked to the aggregated payment)
This is fine for the legacy data, but I actually do want to enforce the 1-N relationship between Contract and Payment going forward. So, using my very unhandy scribble to illustrate, I would like to do this:
I.e. where the payment is aggregate, ContractID will be NULL, otherwise it should not be null. In other words, I need to find a way to enforce the following contingencies on the Payment table:
- ContractID nullable if PaymentID appears in ContractPayment
- ContractID not nullable if PaymentID does not appear in ContractPayment
I don't know how to do this though.
Even if this is possible, it does seem a bit ugly (which legacy data conversion invariably is). So if anyone has a more elegant solution that would be great. Otherwise, anything that works!
Thanks
Karl
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用两个(一组)表,一个用于“旧版”,一个用于未来。您应该能够简单地定义业务规则,而不需要可以为空的列(SQL 的三值逻辑是一场灾难)。可以撤销“旧”表上的权限,以帮助确保它们不再被使用。
Use two (sets of) tables, one for 'legacy' and one going forward. You should be able to define the business rules simply and without the need for nullable columns (SQL's three value logic is a disaster). Privileges could be revoked on the 'legacy' table(s) to help ensure they are not used going forward.