简体   繁体   中英

relational database design scenario

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)

What you want is "negative" foreign key constraints, ie 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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