relational database design scenario

北城余情 提交于 2019-12-24 10:35:51

问题


Consider we have 2 tables like the following:

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).

how can I design such table ? (I'm using mysql BTW)


回答1:


You cannot solve this problem with your current design without interposing some logic at either the trigger or application level. FOREIGN KEYs 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). 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.

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.




回答2:


What you want is "negative" foreign key constraints, i.e. reject product id that's present in this table.

However, that's not possible. You'd have to maintain such a table - that contains only ids from group 1 and 2 - yourself; you could use triggers for that. Afterwards, you would use that table as the foreign key reference table.




回答3:


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. But why not do it on you application? It seems like a business rule to me.



来源:https://stackoverflow.com/questions/12933877/relational-database-design-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!