简体   繁体   English

关系数据库设计方案

[英]relational database design scenario

Consider we have 2 tables like the following: 考虑我们有2个表,如下所示:

products:       id, name
                  (PK = id)
product_group1: product_id
                  (PK = a1_id)
                  (FK = a1_id REFRENCES a1)
product_group2: product_id
                  (PK = a1_id)
                  (FK = a1_id REFRENCES a1)
product_group3: product_id
                  (PK = a1_id)
                  (FK = a1_id REFRENCES a1)

the question is , I want to design a table called approved_products that only accepts products from group1 and group2(not group3). 问题是,我想设计一个名为approved_products的表,它只接受group1和group2(而不是group3)的产品。

how can I design such table ? 我怎么设计这样的表? (I'm using mysql BTW) (我正在使用mysql BTW)

What you want is "negative" foreign key constraints, ie reject product id that's present in this table. 你想要的是“负面的”外键约束,即拒绝该表中存在的产品ID。

However, that's not possible. 但是,这是不可能的。 You'd have to maintain such a table - that contains only ids from group 1 and 2 - yourself; 你必须维护这样一个表 - 它只包含第1组和第2组的ID - 你自己; you could use triggers for that. 你可以使用触发器。 Afterwards, you would use that table as the foreign key reference table. 之后,您将使用该表作为外键引用表。

you should design your tables like if that "rule" didnt exist (because, lets face it, it can change eventually) 你应该设计你的表,好像那个“规则”不存在(因为,让我们面对它,它最终可以改变)

Then, you can use other mechanism to implement this contraint. 然后,您可以使用其他机制来实现此约束。 If you want to do it on a database level, you can use a before insert trigger on the table, or a check on the column that calls a function that verifies the data. 如果要在数据库级别执行此操作,可以在表上使用before insert触发器,或者检查调用验证数据的函数的列。 But why not do it on you application? 但为什么不在你的申请上做呢? It seems like a business rule to me. 对我来说这似乎是一个商业规则。

You cannot solve this problem with your current design without interposing some logic at either the trigger or application level. 您无法在当前设计中解决此问题,而无需在触发器或应用程序级别插入某些逻辑。 FOREIGN KEY s cannot reference more than one table (I understand your design to use one table per product group, if I'm wrong please let me know). FOREIGN KEY不能引用多个表(我理解你的设计每个产品组使用一个表,如果我错了请告诉我)。 In addition they cannot contain any conditional logic, so even if you have a single product_groups table you cannot create a FOREIGN KEY that only allows the G1 and G2 records from that table. 此外,它们不能包含任何条件逻辑,因此即使您有一个product_groups表,也无法创建仅允许该表中的G1和G2记录的FOREIGN KEY

In order to accomplish this with standard relational integrity constraints, you would need an additional table called something like approvable_products which would contain the product_ids of those products that are in group one or group two. 为了使用标准的关系完整性约束来实现这一点,您需要一个名为approvable_products的附加表,其中包含第一组或第二组中那些产品的product_ids

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM